Java
synchronized
method
lock
concurrency

Java synchronized method lock on object, or method?

Interview Questions practice on Codemia

Over 8,000 real interview questions from top companies, searchable by company and role.

Browse interview questions

Understanding Java's synchronized methods can be crucial for ensuring thread safety in your applications. As Java is heavily utilized in concurrent programming, managing access to shared resources is paramount. This article delves into synchronized methods, explaining the nuances of object locking and providing technical examples for better comprehension.

Synchronized Methods in Java

In Java, the synchronized keyword is used to ensure that only one thread at a time can execute a specific block of code or method. Synchronized methods achieve this by acquiring a lock on the object or class the method belongs to.

Types of Locks

  1. Object Level Lock (Instance Method):
    • Synchronized instance methods lock the current object.
    • Only one thread can execute a synchronized instance method at a time for a given object instance.
  2. Class Level Lock (Static Method):
    • Synchronized static methods lock the Class object associated with the class.
    • A lock on a static method ensures that no two threads can execute any static synchronized method of the class simultaneously, regardless of the instance operating in.

Mechanism of Method Locks

Object Lock: When a thread invokes a synchronized instance method, it acquires a lock on the object itself (this). If another thread tries to call another synchronized method on the same object, it will be blocked until the lock is released. Still, other threads can invoke non-synchronized methods freely.

Class Lock: For static synchronized methods, the lock is on the Class object associated with the class. This means the lock is on the class level, not on the object instance level. All threads across any instance of the class will wait if one thread is executing a static synchronized block or method.

Code Example

java
1public class Counter {
2    private int count = 0;
3    
4    // Synchronized instance method
5    public synchronized void increment() {
6        count++;
7    }
8
9    // Non-synchronized instance method
10    public int getCount() {
11        return count;
12    }
13
14    // Synchronized static method
15    public static synchronized void staticSyncMethod() {
16        // Logic for synchronized static method
17    }
18}

In this example:

  • The increment() method uses an object lock. If one thread is executing increment() on an instance of Counter, others will have to wait.
  • The getCount() method is not synchronized and can be accessed concurrently without waiting.
  • staticSyncMethod() locks the Class object, blocking access to all static synchronized methods across any instance.

When to Use Synchronized Methods?

  • Consistency and Thread Safety: Use synchronized methods when you need consistency in mutable data that is accessed by multiple threads.
  • Performance Considerations: While easy to implement for thread safety, synchronized methods can lead to performance bottlenecks if not used judiciously. Consider fine-grained locking or other concurrency utilities if performance becomes an issue.

Alternates to Synchronized Methods

  • Synchronized Blocks: Provide finer control by allowing you to synchronize only portions of code instead of entire methods. Allowing you to use different locks for different operations.
java
1  public void syncBlockExample() {
2      synchronized(this) {
3          // thread-safe operation
4      }
5  }
  • Java Concurrency Utilities (java.util.concurrent): Provide various advanced synchronization constructs like ReentrantLock, Semaphore, CountDownLatch, etc. These provide more flexibility and power than synchronized.

Summary Table

Feature/BenefitSynchronized MethodSynchronized BlockConcurrency Utilities
Lock LevelMethod-level (instance or class)Code blockFine-grained & configurable
OverheadHigher due to method-level lock release and acquireLower by limiting scopeVaries with usage
FlexibilityLess flexible, locks the entire methodMore flexible, can lock part of a methodVery flexible, offers complex synchronization constructs
Use CaseEasy thread safety for methodsOptimal when partial method lock is sufficientComplex applications requiring specialized synchronization

In conclusion, Java synchronized methods provide a simple yet powerful mechanism for enforcing thread safety in multithreaded applications. Nonetheless, combining synchronized blocks and modern concurrency utilities can achieve tailored performance and scalability in more complex systems. Understanding and appropriately implementing these tools can lead to robust and efficient multithreaded applications.


Related reading
Course
Intermediate
27 lessons
14 hours
OOD Fundamentals

Master object-oriented design from first principles, SOLID, design patterns, and classic interview problems with hands-on coding.

View the course
Track what you have practised

A free account saves your progress, solutions and study plan across every problem on Codemia.

Interview Questions practice on Codemia

Over 8,000 real interview questions from top companies, searchable by company and role.

Browse interview questions

All Rights Reserved.