Search code examples
javathread-synchronization

Synchronizing overlapping sets of methods


Imagine a Java class with three methods:

  1. master()
  2. foo()
  3. bar()

I want to synchronize master() and foo() and also master() and bar(), without synchronizing foo() and bar(). It can be done will a separate lock for every pair of synchronized methods, but my actual code has many more than three methods so I was hoping there's a way to do it without so many lock objects.


Solution

  • You are essentially describing a ReadWriteLock. Every two methods are allowed to run simultaneously (a "read lock"), except for master(), which excludes all others (a "write lock"):

    public class MyClass {
        private final ReadWriteLock rwLock = new ReentrantReadWriteLock();
        private final Lock r = rwLock.readLock();
        private final Lock w = rwLock.writeLock();
    
        public void master() {
            w.lock();
            // do stuff
            w.unlock();
        }
    
        public void foo() {
            r.lock();
            // do stuff
            r.unlock();
        }
    
        public void bar() {
            r.lock();
            // do stuff
            r.unlock();
        }
    }