Synchronization in Java
public synchronized void synchronizedMethod() {
// Synchronized method code
}
Note: When a method is declared as synchronized, only one thread can execute it at a time for the same object instance.
Synchronized Blocks
Synchronized blocks allow you to specify a block of code that should be executed by only one thread at a time. The lockObject
serves as a monitor or mutex, ensuring exclusive access to the critical section.
synchronized (lockObject) {
// Critical section of code
}
Intrinsic Locks (Monitors)
synchronized (lockObject) {
// Critical section of code
}
Thread Interaction in Java
'wait()'
, ‘notify()'
, and ‘notifyAll()'
:
These methods are used in conjunction with synchronized blocks to allow threads to wait for a condition and be notified when the condition changes.
synchronized (lockObject) {
while (conditionIsNotMet) {
lockObject.wait();
// Release the lock and wait
}
// Perform actions when the condition is met
}
// In another thread:
synchronized (lockObject) {
// Change the condition
lockObject.notify();
// Notify a waiting thread
}
`BlockingQueue`
: The BlockingQueue interface and its implementations (e.g., LinkedBlockingQueue,
`ArrayBlockingQueue`:
provide a thread-safe way to exchange data between threads. Threads can block until the queue is not empty or not full.
`CountDownLatch:
The CountDownLatch class allows one or more threads to wait until a specified count of operations completes. It’s useful for tasks that depend on multiple subtasks.
`Semaphore:
Semaphores are used to control access to a shared resource by limiting the number of threads that can access it simultaneously.
- Condition Variables: Java also provides
Condition
objects through thejava.util.concurrent.locks
package. These can be used for more fine-grained thread synchronization.
- Thread Interruption: You can use thread interruption to signal a thread to stop its execution. A thread can check its interrupted status using the Thread.isInterrupted() method.