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();
}
}
}