What is the key difference between the volatile keyword and the synchronized keyword in Java?
volatile can be used for blocking threads, while synchronized cannot
volatile ensures visibility of variables across threads, while synchronized ensures mutual exclusion
volatile guarantees atomicity, while synchronized does not
volatile prevents deadlocks, while synchronized does not
Which of the following is the most common cause of a deadlock in multithreading?
Two threads accessing the same variable
Threads requesting resources in a different order
A single thread holding multiple locks
Not using volatile correctly
What does the synchronized keyword synchronize on when used in a non-static method?
The object on which the method is called
The thread calling the method
What will happen if two threads try to acquire two locks in opposite order?
Java
class A {
synchronized void method1(B b) {
b.last();
}
synchronized void last() {}
}
class B {
synchronized void method1(A a) {
a.last();
}
synchronized void last() {}
}
The program will throw an exception
Both threads will run concurrently
What is the primary role of the synchronized keyword in Java?
To guarantee that the method is executed by a single thread
To pause threads for a set period
To ensure that multiple threads are executed simultaneously
To prevent thread starvation
Which of the following statements about deadlocks is false?
Deadlock occurs when two threads hold locks and wait for each other
Deadlock can be avoided by acquiring locks in the same order
Deadlock always leads to an exception
Deadlock can be prevented by using tryLock() in ReentrantLock
How can deadlock be avoided in a multithreading environment?
By synchronizing all methods
By using volatile for all variables
By acquiring locks in a consistent order
What is the purpose of the ReentrantLock in Java?
It provides an atomic way of accessing a shared resource
It supports interruptible lock acquisition
It uses volatile variables to prevent race conditions
It synchronizes method calls automatically
In the following code, which concept is demonstrated in the context of synchronization?
Java
class Geeks {
private int counter = 0;
public synchronized void increment() {
counter++;
}
public synchronized int getCounter() {
return counter;
}
}
Local framework synchronization
Synchronization on a method level
Usage of volatile keyword
What would happen in the following situation involving ReentrantLock?
Java
Lock lock = new ReentrantLock();
lock.lock();
try {
// critical section
lock.lock(); // Reentrant lock acquired again
} finally {
lock.unlock();
lock.unlock(); // Release both locks
}
Successfully acquires and releases the lock
Deadlock prevention fails
There are 10 questions to complete.
Take a part in the ongoing discussion
RetroSearch is an open source project built by @garambo | Open a GitHub Issue
Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo
HTML:
3.2
| Encoding:
UTF-8
| Version:
0.7.4