How can I write to a static field safely in Java? - java

say I had a class that creates objects and keeps track of the number of objects with a static variable. Something like this:
public class Apple {
private static int count = 0;
public Apple () {
count++;
}
public void removeApple() {
count--;
}
}
When I check this code with FindBugs I get the warning Write to static field from instance method, which is obvious of course.
How can I work around this problem and make it more safe and even get rid of that FindBugs Warning??

1. General programming advice
This message is there to warn you about a potential programming mistake because it is a common pitfall for beginner programmers, who are not aware of the differences in the scope of static and instance variables.
However, if you can declare your real version of the removeApple method static without causing any compiler errors, then most probably you should. This would both take care of the warning and make it clear that this method has nothing to do with any specific instance of your class.
2. Concerns related to concurrency
Another aspect of this warning concerns thread safety. If you write to a static field from an instance, that opens the possibility that you'll be doing concurrent updates from different threads, even with no sharing of the class instances between threads.
If you don't need thread safety for your code (which is perfectly fine in general), then you don't need to do anything. If you do need it, then synchronize all updates of the field, or use an AtomicInteger wrapper.
Personally, I'd opt for AtomicInteger because it's the safest option: other options would need you to chase all field updates around the class and make sure they are synchronized. Using AtomicInteger is very simple:
private static final AtomicInteger count = new AtomicInteger();
and then you use count.getAndIncrement() instead of count++.

Use AtomicInteger instead of int primitive.
You might synchronize the method.

You have two choices:
Use AtomicInteger as mentioned by duffmyo
An AtomicInteger is used in applications such as atomically
thread-safe incremented counters.
or
2 . Control the access of the variable by synchronized block
And just from the Findbug error removal perspective:
Logically, we expect instance methods to affect that instance's data.
We expect static methods to affect static data.
Making the counter private and providing the public getter and setter methods will take away that findbug error.

By all probability FindBugs would prefer that removeApple() were static

Related

Thread Safety using final

Here is an example method for explaining thread safety:
class Counter {
private int counter = 0;
public void increment() {
counter++;
}
public int getValue() {
return counter;
}
}
In order to provide thread safety, there are several methods and I would prefer using AtomicInteger approach. However;
1. I am also wondering if I can provide thread safe by using final for the necessary variable(s). If so, how can I perform this?
2. Is one of the reason using final commonly in Java for variables and method arguments to provide thread safety?
In properly synchronized code, the final isn't needed.
E.g. if you would use:
class MyCounter{
private AtomicInteger c = new AtomicInteger();
public int inc(){return c.incrementAndGet();}
public int get(){return c.get();}
}
And you would share the MyCounter-instance with another thread, you need to make sure that there is a happens-before edge between writing c and reading c. This can be done in various ways e.g. you pass the MyCounter-instance to the constructor of some thread (thread start rule). Or you pass it through a volatile field (volatile variable rule) or a synchronized block (monitor lock rule).
This is typically called 'safe publication' and for a correctly synchronized system, this is all you need. If you don't pass the reference safely, you have a data race and weird problems can happen like seeing a partially constructed object. Therefore there is a second mechanism called initialization safety; so no matter if the reference to an object isn't published safely, initialization safety using final will act as a backup solution. The primary use-case for this AFAIK is security.
So for correctly synchronized code, there is no need for final.
That doesn't mean that you should not add finals. It has all kinds of benefits like no accidental changes and it is pretty informative. So I prefer to make as many fields final as possible.
Final has no meaning for method arguments from a memory model perspective, since they are private to a thread. Only shared memory needs to be dealt with in a memory model. Making arguments of a method final is a flavor issue. Some people want it, others don't. I'm not crazy about long method signatures and tend not to add them unless I'm writing some difficult code. But I would be fine if local variables and formal arguments would be final by default (like Rust).
I m just gonna add this with Erwan Daniel's answer .
Your
If you want a counter shared between all your Threads here is another version of your code.
class SharedCounter {
private AtomicInteger sharedCounter ;
public Counter(){
this.sharedCounter = new AtomicInteger(0);
}
public void increment() {
sharedCounter.getAndIncrement();
}
public int value() {
return sharedCounter.get();
}
The final will prevent your atomicInteger12 from changing the object it's using And you can freely set it's value.
final SharedCounter atomicInteger12 = new Counter() ;
No, the final keyword doesn't have anything in common with thread safety.
The final keyword on variables makes them immutable, you can't change their value anymore.
However, it's not like the const keyword in c++ where the whole variable content cannot change. In Java only the reference is immutable.
final AtomicReference<String> toto = new AtomicReference<>("text");
toto.set("new text"); // totally fine
toto = new AtomicReference<>("text"); // does not compile, as toto is immutable reference.
But, there is another keyword that fulfill what you are looking for. It's volatile. https://www.baeldung.com/java-volatile
In short, the value change on all thread simultaneously and is available immediately.
That's what is used in all the Atomic* Java classes.
Ex. https://github.com/AdoptOpenJDK/openjdk-jdk11/blob/master/src/java.base/share/classes/java/util/concurrent/atomic/AtomicInteger.java

Using final in method parameters in Java

As a user newly switching to Java, I have realized that in our project and some other Java projects, final keyword is commonly used and after reading several tutorials and SO threads e.g. Excessive use "final" keyword in Java, I think there is some examples that do not require final keyword. So, here are the points I am confused:
1. Is there any need to use final keyword in method parameters in classes and interfaces? Because
CompanyDTO findByUuid(final UUID uuid);
//or
#Override
public CompanyDTO findByUuid(final UUID uuid) {
//...
}
2. As far as I know, it also good for thread safety, but I need to understand the basic idea on why it is used almost every possible places in Java. Normally it is used for the variables that will not be changed. So, could you please explain the idea of common usage?
Is there any need to use final keyword in method parameters in classes and interfaces?
None. Because the effects of using it are miniscule.
As far as I know, it also good for thread safety
Not at all. A change to a primitive parameter is not visible outside of the method body. On the other hand final doesn't prevent you from invoking a method on a reference type parameter.
In other words: if your method body does something that ends up causing a race condition between different threads, then final doesn't help with that at all.
The absolute only thing that using final for parameters prevents you from doing: re-assigning values to it. So, it can help preventing stupid mistakes. But it almost comes down to pure style. Me for example, I almost never use it, and regard it useless clutter/noise most of the time.
Using final modifier on method parameters doesn't make much sense
since it adds visual clutter to the method declaration without
buying you much. As far as you can make sure that you don't reassign
values to those variables, you are good enough to go without final
modifier on method parameters.
Method parameters lie on the stack, and it is local to that
particular thread as far as that thread doesn't publish it to some
other thread. Since it is not shared between the other threads, no
thread safety issue arises here. However, if the current thread
publishes these arguments, then you are out of luck and the use of
final modifier doesn't give you any thread safety guarantee.
Here's one such a tasteful use of final modifier to write an immutable class which represents a point in our 2-dimensional space.
class Point2D {
private final int x;
private final int y;
Point2D(int x, int y) {
this.x = x;
this.y = y;
}
// Remainder omitted for brevity's sake !
}
Once this class instance is created, you can share it freely with other threads and you don't need to bother synchronizing access to it's state. So, immutable objects give you thread safety for free.
You may read JLS § 17.5 for more details on semantics of final fields.
1. Is there any need to use final keyword in method parameters in classes and interfaces?
It depends on what these methods do.
For example, if they contain lambdas, some rules apply.
See JLS §15.27.2
Any local variable, formal parameter, or exception parameter used but not declared in a lambda expression must either be declared final or be effectively final (§4.12.4), or a compile-time error occurs where the use is attempted.

thread safety in java with an external API object

I have a class from an external API and I want to create an instance of it and access that object's methods from different threads. My questions are as comments in the following code:
import java.util.concurrent.Executors;
public class ThreadSafetyQuestion {
static class ExternalAPIObject {
void method(){
}
}
private static volatile ExternalAPIObject obj;
static synchronized ExternalAPIObject syncGetObject(){
return obj;
}
public static void main(String[] args) {
Executors.newSingleThreadExecutor().submit(()-> {
ThreadSafetyQuestion.syncGetObject().method();//Is this thread safe?
ExternalAPIObject externalAPIObject = ThreadSafetyQuestion.syncGetObject();
//do some other stuff
externalAPIObject.method();//I doubt this is thread safe. How can I access this method from multiple threads in a safe way?
});
}
}
You are looking at this from the wrong perspective. Thread safe means: when more than one thread invokes these methods nothing bad happens. It is really simple: when method() does manipulate "internal data" without any form of synchronisation - then having more than one thread call method() on the same object can result in a problem.
Thus: all the things that you put up in your question do not matter!
The only thing that matters: what exactly do these methods do that you are invoking?! In other words: there is no point in putting up a singleton to call methods in different threads. Or making the object reference volatile. All these ideas add zero in regards of making things "thread safe". Because you still allow method() to be called on the same object by different threads.
What you have to do instead: carefully check what exactly the methods you are invoking are doing.
And in case you don't want to go there: then create a single singleton that simply delegates calls to method() - but that has its methods marked as synchronized.
So: if you don't know anything about the external API - then one conservative approach is to make sure to always all its methods sequentially. Of course that can affect performance in very negative ways.
Long story short: it seems you are lacking basic understanding of multithreading concepts in Java. Don't go for trial/error then - rather step back and study this topic in depth! Seriously: multi-threading errors are subtle, they often go unnoticed for days or months. The first step in avoiding them: knowing what you are doing (instead of throwing some keywords at a problem that you somehow read about having this or that effect).

Java Thread Safety: How to handle an instance variable when you have to call methods on it

So I'm pretty good overall when it comes to the thread-safety of code, but I'm currently encountering a situation where I'm not clear on the best way to handle it.
I have an instance variable, non-final because the enclosing class can change its value. This variable is an object that has several methods that get called on it during the application. Here is a quick sample to show what I mean.
private class Foo{
private FooFoo fooFoo;
public synchronized void setFooFoo(FooFoo fooFoo){
this.fooFoo = fooFoo;
}
public void doSomething(){
fooFoo.doSomething(); //How do I make this line thread-safe?
}
}
Changing the reference of the fooFoo field is easy, just simple synchronization. But what about when the doSomething() method is called on fooFoo? I'm always hesitant to synchronize on an alien method due to deadlock risk.
In the real cases this is based on, there are many different variations of this. My company's application is a sprawling code base that frequently resembles a bowl of spaghetti, so when it comes to writing any kind of synchronized code I'm extra paranoid, because of the tight coupling and the fact that there are developers not only here in the US, but in an offshore firm in eastern europe working on it and I do not trust all of them to make good coding decisions.
So I'm just looking for the best practice to handle this kind of situation in a multi-threaded environment. Thanks.
fooFoo.doSomething(); //How do I make this line thread-safe?
Hint: You can't make that one line thread-safe unless that is the only line in the whole program that ever accesses the object.
Thread-safety is not about making particular lines of code or particular methods thread safe: It's about making data thread safe.
Does fooFoo refer to a mutable object? If not, then that line already is thread safe. But if the object is mutable, then thread-safety, at a minimum, means insuring that unintended interactions between two or more threads can not put that object into an invalid state; and at the worst case it means insuring the consistency of relationships between the fooFoo object and other objects in your program.
Any time there is an important relationship between two or more pieces of data that are shared between threads, then you probably need to throw a synchronized block around any bit of code that could temporarily violate that relationship, and you need to throw a synchronized block around any bit of code that depends on that relationship---even if the code only looks at the data.
In your case you would have to make doSomething() synchronized too, because you need to lock every time a concurrent access on a mutable part of the class occurs. While you are only reading fooFoo in doSomething, you could at the same time be writing fooFoo in setFooFoo(), thus creating a data race. synchronized essentially causes the function call to take a lock that is associated with the Java-object at entry and to release it once you leave the function.
Alternatively you can use a Lock member inside Foo that you take when you do either. This applies in situations, where you may have multiple independent members that may be accessed safely while the other is being altered. In this case taking two different locks may make your code substantially faster.
For completeness sake it should be mentioned that in some older Java versions (Java 5 only I believe) taking the intrinsic lock of the object through a synchronized method, was substantially slower than using a lock object.
For the deadlock problem: you are right to worry about this, but consider it as a separate issue, after you make your object thread-safe in the first place. The question there is what other locks are taken and it is not possible to answer this with just what you posted. Given your object, synchronizing the read/write on the object can not deadlock by itself, because only one operation can be active at the time, and they do not take any other locks from what you show in your code.
It depends upon what your concerns are for thread safety.
If foo is only delegated to you can simply make it volatile. This will prevent threads from cashing a reference to the old value if the reference is updated. FooFoo can then handle it's own thread safety concerns.
private class Foo{
private volatile FooFoo fooFoo;
public void setFooFoo(FooFoo fooFoo){
this.fooFoo = fooFoo;
}
public void doSomething(){
fooFoo.doSomething();
}
}
If your concern is about thread safety of Foo itself, and it is doing more then just delegating calls you should synchronize relevant methods.
private class Foo{
private FooFoo fooFoo;
public synchronized void setFooFoo(FooFoo fooFoo){
this.fooFoo = fooFoo;
}
public synchronized void doSomething(){
fooFoo.doSomething();
}
public synchronized void doSomethingElse() {
int values = fooFoo.getValue();
// do some things
fooFoo.setValue(values + somethingElse);
}
}

Synchronization concerns with a static method in java

Suppose I have a Utility class,
public class Utility {
private Utility() {} //Don't worry, just doing this as guarantee.
public static int stringToInt(String s) {
return Integer.parseInt(s);
}
};
Now, suppose, in a multithreaded application, a thread calls, Utility.stringToInt() method and while the operation enters the method call, another thread calls the same method passing a different s.
What happens in this case? Does Java lock a static method?
There is no issue here. Each thread will use its own stack so there is no point of collision among different s. And Integer.parseInt() is thread safe as it only uses local variables.
Java does not lock a static method, unless you add the keyword synchronized.
Note that when you lock a static method, you grab the Mutex of the Class object the method is implemented under, so synchronizing on a static method will prevent other threads from entering any of the other "synchronized" static methods.
Now, in your example, you don't need to synchronize in this particular case. That is because parameters are passed by copy; so, multiple calls to the static method will result in multiple copies of the parameters, each in their own stack frame. Likewise, simultaneous calls to Integer.parseInt(s) will each create their own stack frame, with copies of s's value passed into the separate stack frames.
Now if Integer.parseInt(...) was implemented in a very bad way (it used static non-final members during a parseInt's execution; then there would be a large cause for concern. Fortunately, the implementers of the Java libraries are better programmers than that.
In the example you gave, there is no shared data between threads AND there is no data which is modified. (You would have to have both for there to be a threading issue)
You can write
public enum Utility {
; // no instances
public synchronized static int stringToInt(String s) {
// does something which needs to be synchronised.
}
}
this is effectively the same as
public enum Utility {
; // no instances
public static int stringToInt(String s) {
synchronized(Utility.class) {
// does something which needs to be synchronised.
}
}
}
however, it won't mark the method as synchronized for you and you don't need synchronisation unless you are accessing shared data which can be modified.
It should not unless specified explicitly. Further in this case, there wont be any thread safety issue since "s" is immutable and also local to the method.
You dont need synchronization here as the variable s is local.
You need to worry only if multiple threads share resources, for e.g. if s was static field, then you have to think about multi-threading.

Categories