javamultithreading

How to implement a thread-safe class with a setter and a getter function where the frequency of using setter is way higher than getter


Let's say we want a thread-safe class called Adder, and there is an add function and a get function

class Adder {
    int counter;
    public void add(int a) counter += a;
    public int get() return counter;

Right now it is apparently not thread safe. Now given that the frequency of using add() function is 80% and using get() is 20%. Also, we allow getting a counter with a lag so the get function does not need to be thread safe. How should we implement this? Apparently adding synchronized keyword to add() isnt a good solution since too many threads will try to obtain the lock and there will a race condition.

Also, the add() function should always be successful (meaning that you cannot use non-blocking locking)


Solution

  • You can solve this problem with AtomicInteger in Java:

    import java.util.concurrent.atomic.AtomicInteger;
    
    public class Adder {
    
        private final AtomicInteger counter = new AtomicInteger(0);
    
        public int add(int delta) {
            return counter.addAndGet(delta);
        }
    
        public int get() {
            return counter.get();
        }
    }