In Java, the synchronized keyword is used for code blocks and methods where thread-safe matters and for multi-threaded (concurrent) programming. A synchronized method or a synchronized statement can be executed by only one thread at a time.
The syntax for a synchronizedmethod is as follows:
<method modifier> synchronized <method signature> { // synchronized code block }
The syntax for a synchronizedstatement is as follows:
synchronized (expression) { // synchronized code block }
- The expression must be evaluated to a reference type, i.e an object reference.
- The current executing thread will try to acquire a lock before executes the synchronized code block:
- If the lock is not acquired by any thread, the current executing thread will own the lock and execute the synchronized code block.
- While the current executing thread owns the lock, no other threads can acquire that lock.
- When the synchronized code block completes, the current executing thread releases the lock.
- There is no something called “synchronized constructor”.
The following code example illustrates the synchronized keyword is applied for a static method:
class Counter { private static int count; static synchronized void increase() { count++; } }
The following code example shows instance methods are synchronized:
class BankAccount { private double balance; synchronized void withdraw(double amount) { this.balance -= amount; } synchronized void deposit(double amount) { this.balance += amount; } }
The following code example shows a synchronized statement is applied for a code block, not a method:
Object lock = new Object(); synchronized (lock) { System.out.println("Synchronized statement"); }
See all keywords in Java.