What is the purpose of the synchronized keyword in Java?
sobes.tech AI
Answer from AI
synchronized in Java is used to control access to shared resources in a multithreaded environment. It guarantees that only one thread can execute a specific block of code or method at any given time, preventing Conditions.
1. Synchronization of methods:
Can be applied to an instance or static method.
-
Instance method: Synchronizes access to the object on which the method is called.
class MyClass { public synchronized void myMethod() { // Multithreaded code } } -
Static method: Synchronizes access to the class to which the method belongs.
class MyClass { public static synchronized void myStaticMethod() { // Multithreaded code } }
2. Synchronization of blocks:
Allows synchronizing a part of a method using a monitor object. The object specified in parentheses is the lock.
class MyClass {
private Object lock = new Object();
public void anotherMethod() {
synchronized (lock) {
// Multithreaded code
}
}
}
3. Types of locks:
- Object monitor: Each object in Java has an associated monitor.
synchronizeduses this mechanism. - Mutex (Mutual Exclusion): Ensures that only one thread can access the protected resource at a time.
4. Properties:
- Atomicity: Ensures that an operation is completed entirely or not at all, without interruption by another thread.
- Visibility: Guarantees that changes made by one thread within a synchronized block/method are visible to other threads entering a synchronized block/method on the same monitor.
- Ordering: Threads waiting to enter a synchronized block/method get access in FIFO order, although this is not strictly guaranteed by the JLS specification for all JVM implementations.
5. Usage:
Used to protect access to shared data or resources to avoid multithreading issues such as data races or inconsistent object states.
synchronized is effective for simple synchronization scenarios but can create bottlenecks under high contention and lead to deadlocks if used improperly. More advanced and performant mechanisms from the java.util.concurrent package, such as Lock or Semaphore, can be used in complex scenarios.