Reputation: 861
I have the following class in my application
public class InsertErrorLinesHandler {
private int currentCount;
public void insertErrorLine() {
//do something...
currentCount++;
}
}
And I have multiple threads that are using the same instance of InsertErrorLinesHandler
, particulary calling insertErrorLine method. After all these threads are stopped, I get the currentCount
from this instance.
The question is - how to rewrite this class to be sure that there won't be any concurrency problems? What I want is to be sure, that currentCount
value will be the count of method callings from threads. Should I use static method and static variable? Make method synchronize? Make variable volatile?
Thanks!
Upvotes: 5
Views: 6399
Reputation: 27115
So far, nobody's addressed this part of your question:
Should I use static...?
The choice of whether or not to use static
is completely independent of the choice of whether to use synchronized
or AtomicInteger
or not. The answer depends on what you want to count.
A static
field in Java is what some other languages call a global variable: There is only one of it for the entire program. A non-static field (a.k.a., an instance variable) exists in multiple copies---one for each instance of the class to which it belongs.
How many instances of the InsertErrorLineHandler
class does your program create? If more than one, then do you want each instance to have its own counter
, or do you want all of them to share the same counter
? Declaring the field static
means that they will all share the same, and leaving out the static
keyword means that each instance will have its own counter.
If your program only ever creates one InsertErrorLineHandler
instance (i.e., if you are using it as a singleton class) then you should not use static
. Making fields static
or not static won't change the behavior of a singleton, but using static
in a singleton would be bad style.
Upvotes: 2
Reputation: 5173
Use AtomicInteger or use LongAdder when number of threads are more for better performance.
Here is the example on how to use AtomicInteger,
public class InsertErrorLinesHandler {
AtomicInteger counter = new AtomicInteger();
public void insertErrorLine() {
counter.incrementAndGet();
}
public int get() {
return counter.get();
}
}
Upvotes: 2
Reputation: 43088
Simple fix, make the method call synchronized:
public class InsertErrorLinesHandler {
private int currentCount;
public void synchronized insertErrorLine() {
//do something...
currentCount++;
}
}
Upvotes: 3
Reputation: 18148
I suggest using an AtomicInteger, which has a thread-safe increment method
Upvotes: 9