Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java - multithreading increment

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!

like image 862
another-programmer Avatar asked Dec 05 '22 21:12

another-programmer


2 Answers

I suggest using an AtomicInteger, which has a thread-safe increment method

like image 53
Zim-Zam O'Pootertoot Avatar answered Dec 14 '22 20:12

Zim-Zam O'Pootertoot


Simple fix, make the method call synchronized:

public class InsertErrorLinesHandler {

    private int currentCount;

    public void synchronized insertErrorLine() {
        //do something...
        currentCount++;
    }
}
like image 43
smac89 Avatar answered Dec 14 '22 19:12

smac89