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.
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
- 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.
- Class Level Lock (Static Method):
- Synchronized static methods lock the
Classobject 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
In this example:
- The
increment()method uses an object lock. If one thread is executingincrement()on an instance ofCounter, others will have to wait. - The
getCount()method is not synchronized and can be accessed concurrently without waiting. staticSyncMethod()locks theClassobject, 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 Concurrency Utilities (
java.util.concurrent): Provide various advanced synchronization constructs likeReentrantLock,Semaphore,CountDownLatch, etc. These provide more flexibility and power thansynchronized.
Summary Table
| Feature/Benefit | Synchronized Method | Synchronized Block | Concurrency Utilities |
| Lock Level | Method-level (instance or class) | Code block | Fine-grained & configurable |
| Overhead | Higher due to method-level lock release and acquire | Lower by limiting scope | Varies with usage |
| Flexibility | Less flexible, locks the entire method | More flexible, can lock part of a method | Very flexible, offers complex synchronization constructs |
| Use Case | Easy thread safety for methods | Optimal when partial method lock is sufficient | Complex 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
- Java synchronized method lock on object, or method?
- Java thread executing remainder operation in a loop blocks all other threads
- Java Thread Garbage collected or not
- java thread reuse
- Java system properties and environment variables
- Java System.currentTimeMillis equivalent in C
- Java Thread.currentThread.sleepx vs. Thread.sleepx
- Java threads ExecutorService delay between threads

OOD Fundamentals
Master object-oriented design from first principles, SOLID, design patterns, and classic interview problems with hands-on coding.
View the courseTrack 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.