What Cases Require Synchronized Method Access in Java?

前端 未结 6 1145
醉酒成梦
醉酒成梦 2020-12-13 14:53

In what cases is it necessary to synchronize access to instance members? I understand that access to static members of a class always needs to be synchronized- because they

6条回答
  •  时光取名叫无心
    2020-12-13 15:38

    To simply put it, you use synchronized when you have mutliple threads accessing the same method of the same instance which will change the state of the object/or application.

    It is meant as a simple way to prevent race conditions between threads, and really you should only use it when you are planning on having concurrent threads accessing the same instance, such as a global object.

    Now when you are reading the state of an instance of a object with concurrent threads, you may want to look into the the java.util.concurrent.locks.ReentrantReadWriteLock -- which in theory allows many threads to read at a time, but only one thread is allowed to write. So in the getter and setting method example that everyone seems to be giving, you could do the following:

    public class MyClass{
        private ReentrantReadWriteLock rwl = new ReentrantReadWriteLock();
        private int myValue = 0;
    
        public void setValue(){
            rwl.writeLock().lock();
            myValue++;
           rwl.writeLock().unlock();
        }
    
        public int getValue(){
           rwl.readLock.lock();
           int result = myValue;
           rwl.readLock.unlock();
           return result;
        }
    }
    

提交回复
热议问题