- Details
- Written by Nam Ha Minh
- Last Updated on 20 August 2019   |   Print Email
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
}
Some Rules about synchronized keyword:
- 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:
- For synchronized statement: the monitor associates with the object returns by the expression.
- For synchronized method:
- If the method is static, the lock associates with the Class object of the class in which the method is declared.
- If the method is non-static, the lock associates with this – the object for which the method is invoked.
- 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”.
Java synchronized keyword Examples:
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. Related Topics:
Other Recommended Tutorials:
About the Author:
Nam Ha Minh is certified Java programmer (SCJP and SCWCD). He started programming with Java in the time of Java 1.4 and has been falling in love with Java since then. Make friend with him on
Facebook and watch
his Java videos you YouTube.