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();
        } 
    }
}
Trinimon
  • 13,839
  • 9
  • 44
  • 60
Student3794
  • 31
  • 2
  • 5
  • http://docs.oracle.com/javase/7/docs/api/java/util/concurrent/locks/Lock.html – gladiola May 13 '15 at 20:54
  • 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. – Louis Wasserman May 13 '15 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 '15 at 22:31

1 Answers1

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.

adhg
  • 10,437
  • 12
  • 58
  • 94