Java synchronized keyword examples
- 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:
- 9 Rules about Constructors in Java
- 12 Rules and Examples About Inheritance in Java
- 12 Rules of Overriding in Java You Should Know
- 10 Java Core Best Practices Every Java Programmer Should Know
- Understand Interfaces in Java
- Understand how variables are passed in Java
- Understand encapsulation in Java
Comments
I think your example with the BankAccount and the two synchronized methods is incorrect, you won't be able to call the same method twice if the first is still occuring, but both methods could be called at the same time and access the same variable, it is preferable to use a Lock instance stored within this class and used by these two methods before and after their action