Course Content
Advanced Java 2077
Advanced Java 2077
Synchronization and Locks
When multiple threads access a shared resource, there is a risk of race conditions and other synchronization problems. Synchronization and locks provide a way to coordinate access to shared resources and avoid these problems.
Synchronization
Synchronization is the process of controlling access to shared resources by multiple threads. In Java, synchronization is achieved using the synchronized keyword, which can be used to mark a method or a code block as synchronized.
Here is an example of a synchronized method.
Main
class Counter { private int count = 0; public synchronized void increment() { count++; } public synchronized void decrement() { count--; } public synchronized int getCount() { return count; } }
In this example, the increment()
, decrement()
, and getCount()
methods are all marked as synchronized
. This means that only one thread can access these methods at a time, ensuring that the count variable is accessed safely and consistently.
Locks
Locks are another way to achieve synchronization in Java. Unlike the synchronized keyword, locks provide more fine-grained control over synchronization, allowing for more complex synchronization scenarios.
Here is an example of using locks to achieve synchronization.
Main
import java.util.concurrent.locks.Lock; import java.util.concurrent.locks.ReentrantLock; class Counter { private int count = 0; private Lock lock = new ReentrantLock(); public void increment() { lock.lock(); try { count++; } finally { lock.unlock(); } } public void decrement() { lock.lock(); try { count--; } finally { lock.unlock(); } } public int getCount() { lock.lock(); try { return count; } finally { lock.unlock(); } } }
In this example, we create a Counter
class that uses a ReentrantLock
to achieve synchronization. The increment()
, decrement()
, and getCount()
methods all acquire and release the lock
using the lock()
and unlock()
methods, ensuring that only one thread can access the count variable at a time.
Thanks for your feedback!