<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”.
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;
}
}Object lock = new Object();
synchronized (lock) {
System.out.println("Synchronized statement");
}See all keywords in Java.
Nam Ha Minh is certified Java programmer (SCJP and SCWCD). He began programming with Java back in the days of Java 1.4 and has been passionate about it ever since. You can connect with him on Facebook and watch his Java videos on YouTube.