I wrote a simple program to learn about synchronized block. The program is as follow:
public class SychronizedBlock {
static int balance = 0;
static Integer lock = 0;
public static void deposit(int amt) {
Thread t1 = new Thread(new Runnable() {
public void run() {
acquire_lock();
int holdings = balance;
balance = holdings + amt;
System.out.println("deposit " + amt + ", balance: " + balance);
release_lock();
}
});
t1.start();
}
public static void acquire_lock() {
synchronized(lock) {
while (lock == 1) {
try {
lock.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
lock = 1;
}
}
public static void release_lock() {
synchronized(lock) {
lock = 0;
lock.notifyAll();
}
}
public static void test1() {
balance = 0;
deposit(500);
deposit(500);
}
public static void main(String[] args) {
test1();
}
}
However, when running the program, I met with an IllegalMonitorStateException. I think I have place the wait() and notifyAll() function in the synchronized block, and I have set the lock as parameter of synchronized. Why do I still have Exception?
Problem is with your release_lock
method. You are reassigning lock
to 0
before calling lock.notifyAll().
Which means the notifyAll will be called on a new Integer object which is not locked. Change the code to following to fix the issue.
public static void release_lock() {
synchronized(lock) {
lock.notifyAll();
lock = 0;
}
}