Allow multiple gets for synchronized getter/setter

concurrency, java, multithreading, synchronized

Solution

Take a look at the ReadWriteLock. This interface is what you are looking for, it allows for mutliple readers but only one writer.

An example:

private int foo = 0;

private ReadWriteLock rwLock = /* use some implementation of ReadWriteLock here */;

public int get() {
    Lock l = rwLock.readLock();
    int result = 0;
    l.lock();
    try {
        result = this.foo;
    }
    catch(Exception ex) {
        // may throw the Exception here
    }
    finally {
        l.unlock();
    }
    return result;
}

public void set(int bar){ 
    Lock l = rwLock.writeLock();
    l.lock();
    try {
        this.foo = bar;
    }
    catch(Exception ex) {
        // may throw the Exception here
    }
    finally {
        l.unlock();
    }
}

Problem

A common way of gaining access to a field is to synchronize the getters and setters. A simple example with an int would look like: ``` private int foo = 0; public synchronized int get(){return this.foo;} public synchronized void set(int bar){ this.foo = bar;} ``` Now, while this is a safe way of making the access thread safe, it also reveals that only one thread can read `foo` at a time. If many threads where to read `foo` very often, and only sometimes update this variable, it would be a big waste. The getter instead could be called by multiple threads simultaneously without any problem. Are there any established patterns about how to deal with this? Or how would you get around this in the most elegant way?

Original source