Java
synchronized
object lock
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

Java, a widely-used programming language, offers multiple mechanisms for thread synchronization. Among them, the synchronized keyword is prominent for ensuring that a resource, such as an object or method, is not accessed concurrently by multiple threads in a way that could cause inconsistent data states or interruptions. Understanding how Java's synchronized method works, and what the lock applies to, is crucial for developing robust multithreaded applications. This article explores the intricacies of synchronized methods and locks in Java.

Synchronized Methods and Locks

In Java, synchronization is used to control the access of multiple threads to shared resources. When a method is declared as synchronized, it locks the object or class on which the method is being called. The form of synchronization—whether it's on the instance of an object or on the class—depends on whether the method is an instance method or a static method.

Synchronized Instance Methods

A synchronized instance method acquires a lock on the current instance of the class, i.e., this object. If one synchronized instance method is executing on a particular object, no other synchronized instance method on the same object can execute until the first method finishes its execution. This doesn't affect methods on different instances.

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    public int getCount() {
10        return count;
11    }
12}

In this example, when the increment() method is called, the lock is acquired on the instance of Counter (this). Any other thread trying to access the increment() method, or any other synchronized instance method on the same Counter instance, will block until the lock is released.

Synchronized Static Methods

When a static method is declared as synchronized, the lock is acquired on the class's Class object, not the instance of the class. This means if the lock is held on a static method, no other synchronized static method for that class can be executed in any thread.

Example

java
1public class SyncDemo {
2  
3    // Synchronized static method
4    public static synchronized void staticSyncMethod() {
5        // critical section
6    }
7}

Here, the lock is on the SyncDemo.class object. Threads attempting to execute other synchronized static methods (like staticSyncMethod) on SyncDemo will be blocked if one method already holds the lock.

Key Points Summary

AspectSynchronized Instance MethodSynchronized Static Method
Lock Applies ToCurrent object (this)Class object (ClassName.class)
Impact on ExecutionBlocks other synchronized methodsBlocks other synchronized static
on the same instancemethods in the class

Synchronization Best Practices

While synchronized methods are essential for thread safety, they should be used judently to avoid bottlenecks:

  • Minimize Scope: Only synchronize the critical section of code to avoid holding up other threads unnecessarily.
  • Avoid Nested Locks: This reduces the risk of deadlocks.
  • Use Alternatives When Appropriate: Consider using java.util.concurrent classes like ReentrantLock, ReadWriteLock, or Atomic classes, which offer more flexibility and better performance in some scenarios.

Conclusion

Java's synchronized methods and the locks they apply to—whether on an instance or a class—are fundamental constructs for managing access to shared resources in multithreaded environments. Their proper usage ensures data consistency and program correctness, though care must be taken to prevent common pitfalls like deadlocking or unnecessary performance hits. Through careful design and understanding of these concepts, developers can harness the power of Java's concurrency features to build efficient and reliable 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.