Skip to main content

Resolve issues with thread lock code - I

Couple of improvements can be done with the code below

  1. Lock is obtained twice when setI() method is called.  Though Lock is re-entrant this is not necessary.  setI() doesn't have to obtain the lock.  Having said that this is common in real world where one function calls other and both may have to obtain locks.
  2. Other improvement is usage of ReadWriteLock.  getI() method being a read only method can obtain readLock and setI() can get a writeLock.  See example code here

public class LockIssue {
    private int i;
    private Lock l = new ReentrantLock();

    public int getI() {
        try {
            l.lock();
            return i;
        } finally {l.unlock();}
    }

    public void setI(int i) {
        try {
            l.lock();
            reallySetI(i);
        } finally {l.unlock();}
    }

    private void reallySetI(int i ) {
        try {
            l.lock();
            this.i = i;
        } finally {l.unlock();}
    }
}

Comments