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!
I suggest using an AtomicInteger, which has a thread-safe increment method
Simple fix, make the method call synchronized:
public class InsertErrorLinesHandler {
    private int currentCount;
    public void synchronized insertErrorLine() {
        //do something...
        currentCount++;
    }
}
                        If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With