Synchronized
Explore how synchronization works in Java multi-threading and understand common errors like object reassignment leading to IllegalMonitorState exceptions. This lesson helps you identify synchronization mistakes and improve thread safety in your Java programs.
We'll cover the following...
We'll cover the following...
1.
What is synchronized?
Show Answer
Did you find this helpful?
Technical Quiz
1.
Consider the code snippet below:
class NewbieSynchronization {
Boolean flag = new Boolean(true);
public void example() throws InterruptedException {
Thread t1 = new Thread(new Runnable() {
public void run() {
synchronized (flag) {
try {
while (flag) {
System.out.println("First thread about to sleep");
Thread.sleep(5000);
System.out.println("Woke up and about to invoke wait()");
flag.wait();
}
} catch (InterruptedException ie) {
}
}
}
});
Thread t2 = new Thread(new Runnable() {
public void run() {
flag = false;
System.out.println("Boolean assignment done.");
}
});
t1.start();
Thread.sleep(1000);
t2.start();
t1.join();
t2.join();
}
}
What will be the output of invoking the example() method ?
A.
InterruptedException is thrown
B.
IllegalStateException is thrown
C.
Program runs without issues
D.
Thread t2 doesn’t synchronize on the same object as thread t1
1 / 1
A classic ...