java method synchronization and read/write mutual exclusion

后端 未结 5 1467
醉酒成梦
醉酒成梦 2021-02-01 05:28

I have two methods read() and write() as below in a class.

class Store
{

  public void write()
  {
    // write to store;
  }

  publi         


        
5条回答
  •  梦毁少年i
    2021-02-01 05:49

    The best option in this case is to use a reader-writer lock: ReadWriteLock. It allows a single writer, but multiple concurrent readers, so it's the most efficient mechanism for this type of scenario.

    Some sample code:

    class Store
    {
        private ReadWriteLock rwlock = new ReentrantReadWriteLock();
    
        public void write()
        {
           rwlock.writeLock().lock();
           try {
              write to store;
           } finally {
              rwlock.writeLock().unlock();
           }
        }
    
        public String read()
        {
           rwlock.readLock().lock();
           try {
              read from store;
           } finally {
              rwlock.readLock().unlock();
           }
        }
    }
    

提交回复
热议问题