1

I understand that synchronization allows for implicit locks, but don't these produce the same results?

What is difference between the following two sections of code? Why would a programmer choose to use each?

Code block #1

class PiggyBank {    
    private int balance = 0; 
    public int getBalance() {
        return balance; 
    }
    public synchronized void deposit(int amount) { 
        int newBalance = balance + amount;
        try {
            Thread.sleep(1);
        } catch (InterruptedException ie) {
            System.out.println("IE: " + ie.getMessage());
        }
        balance = newBalance;
    }
}

Code block #2

class PiggyBank {
    private int balance = 0;
    private Lock lock = new ReentrantLock(); 

    public int getBalance() {
        return balance; 
    }
    public void deposit(int amount) { 
        lock.lock();
        try {
            int newBalance = balance + amount; 
            Thread.sleep(1);
            balance = newBalance;
        } catch (InterruptedException ie) { System.out.println("IE: " + ie.getMessage());
        } finally { 
            lock.unlock();
        } 
    }
}
3
  • Yes, those look equivalent. Most programmers would choose option 1 in this case, but you might need locks in more sophisticated contexts where you need more control. May 13, 2015 at 20:54
  • 1
    Both are error prone as the read of balance should be volatile or under the lock. The synchronized version leaks the lock which is a poor practice.
    – Ben Manes
    May 13, 2015 at 22:31

1 Answer 1

3

Both of your examples you provided will serve the same purpose and they are equal in terms of thread-safe (I would also volatile your balance). ReentrantLock is more 'unstructured', this means that you can lock a critical section in one method and unlock it in another method; something you cannot do with synchronized because it's structure on a block.

There's also a performance issue where you want to utilize ReentrantLock over synchronized but that is true only when involving multiple threads.

Not the answer you're looking for? Browse other questions tagged or ask your own question.