Sunday, January 19, 2025
HomeProgrammingJava - What Does ‘Synchronized’ Mean?

Java – What Does ‘Synchronized’ Mean?

In Java, the synchronized keyword is used to handle thread synchronization. It ensures that only one thread can access a synchronized method or block at a time, thereby preventing race conditions and ensuring thread safety.

Where is synchronized Used?

  1. Synchronized Methods: Restrict access to a method so that only one thread can execute it at a time.
  2. Synchronized Blocks: Restrict access to a specific section of code within a method.

Why Use synchronized?

When multiple threads try to access shared resources (like variables or objects) concurrently, it can lead to inconsistent or incorrect results. The synchronized keyword ensures that only one thread accesses a critical section at any given time, preserving data consistency.

How Does synchronized Work?

Every object in Java has an intrinsic lock (or monitor) associated with it. When a thread enters a synchronized method or block, it acquires the lock. Other threads attempting to enter a synchronized section on the same object must wait until the lock is released.

See also  Java String Length Method with Examples

Types of synchronized Usage

1. Synchronized Methods

A method can be declared synchronized, which locks the entire method.

Example:

class Counter {
    private int count = 0;

    // Synchronized method
    public synchronized void increment() {
        count++;
    }

    public int getCount() {
        return count;
    }
}

public class Main {
    public static void main(String[] args) {
        Counter counter = new Counter();

        // Multiple threads increment the counter
        Thread t1 = new Thread(() -> counter.increment());
        Thread t2 = new Thread(() -> counter.increment());

        t1.start();
        t2.start();
    }
}

Explanation:

  • The increment method is synchronized. Only one thread can execute it at a time, ensuring count is updated safely.
See also  What do \t and \b do?

2. Synchronized Blocks

Instead of locking the entire method, you can synchronize only a specific block of code.

Example:

class Counter {
    private int count = 0;

    public void increment() {
        // Synchronized block
        synchronized (this) {
            count++;
        }
    }

    public int getCount() {
        return count;
    }
}

Explanation:

  • The synchronized block locks only the critical section of code, improving efficiency by not locking the entire method.3. Static Synchronized Methods

A static synchronized method locks the class object, not an instance.

Example:

class SharedResource {
    public static synchronized void displayMessage(String message) {
        System.out.println("Message: " + message);
    }
}

Explanation:

  • Only one thread can execute a static synchronized method on the class at a time.

Important Points About synchronized

  1. Locks: Each object has a single intrinsic lock. For synchronized static methods, the class itself is locked.
  2. Performance: Synchronization adds overhead, so use it only when necessary.
  3. Deadlocks: Be cautious while using multiple synchronized blocks to avoid deadlocks.
  4. Reentrancy: The synchronized keyword is reentrant, meaning a thread can acquire the same lock multiple times without blocking itself.
See also  What is Array?

When to Avoid synchronized

  • If the operation is read-only and no shared resource is being modified, synchronization is unnecessary.
  • Use high-level concurrency utilities like java.util.concurrent for better performance in complex scenarios.
RELATED ARTICLES
0 0 votes
Article Rating

Leave a Reply

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
- Advertisment -

Most Popular

Recent Comments

0
Would love your thoughts, please comment.x
()
x