Search code examples
javamultithreadingconcurrencyatomicoperation

How provide in java atomic read/write of 2 variables together?


In my class I have code like:

int counter1;
int counter2;

public void method1(){
 if (counter1>0) {
  ...........do something
   if (counter2>0) {
    ....do something else
    }
}

public void method2() {
  counter1=0;
  counter2=0;
}

I need that both counters set together. I am afraid that OS can to method1 can be invoked after setting counter1 only. Does it possible? Thanks.


Solution

  • Either use the synchronized keyword as the other answer suggest or use the ReentrantReadWriteLock if you have more reads than writes to the counter, for better performance. You can read about the lock here http://docs.oracle.com/javase/7/docs/api/java/util/concurrent/locks/ReentrantReadWriteLock.html

    private int counter1;
    private int counter2;
    private final ReentrantReadWriteLock rwl = new ReentrantReadWriteLock();
    private final Lock r = rwl.readLock();
    private final Lock w = rwl.writeLock();
    
    public void method1(){
       r.lock();
       try { 
         if (counter1>0) {
            ...........do something
         if (counter2>0) {
            ....do something else
         }
       } finally { r.unlock(); }
    
    }
    
    public void method2() {
      w.lock();
      try { 
        counter1=0;
        counter2=0; 
      } finally { w.unlock(); }
    
    }