How to use the synchronized keyword?
There are two syntactic forms based on the synchronized keyword, methods and blocks. A synchronized method acquires a lock before it executes. For example, the following synchronized method
class MyClass {
public synchronized void function() {
....
}
}
is equivalent to the following synchronized block
class MyClass {
public void function() {
synchronized(this) {
....
}
}
}
Few notes about synchronized keyword:
- The constructors and initializers cannot be synchronized and a compiler error will occur if you put synchronized front of a constructor. But constructors and initializers of a class can contain synchronized blocks. For example,
class MyClass {
static int x = 0;
static int y = 0;
{
synchronized(MyClass.class) {
x++;
}
}
public MyClass() {
synchronized(MyClass.class) {
y++;
}
}
} - Although the synchronized keyword can appear in a method header, the synchronized keyword is not part of the method signature. Therefore, it is not automatically inherited when subclasses override superclass methods. The synchronized methods can be overrided to be non-synchronous. The synchronized instance methods in subclasses use the same locks as their superclasses.
- The interface's methods cannot be declared synchronized. The Synchronization is part of the implementation but not part of the interface.
- The synchronization of an Inner Class is independent on it's outer class. That means locks on inner/outer objects are independent. Getting a lock on outer object doesn??t mean getting the lock on an inner object as well, that lock should be obtained separately
- A non-static inner class method can lock it's containing class by using a synchronized block. The inner class can reference the outer class with OuterClass.this:
synchronized(OuterClass.this) {
....
}
Reference
Concurrent Programming in Java : Design principles and patterns by Doug Lea
Most Recent java Faqs
- How to uncompress a file in the gzip format?
- How to make a gzip file in Java?
- How to use Java String.split method to split a string by dot?
- How to validate URL in Java?
- How to schedule a job in Java?
- How to return the content in the correct encoding from a servlet?
- What is the difference between JDK and JRE?
Most Viewed java Faqs
- How to read input from console (keyboard) in Java?
- How to use HttpURLConnection POST data to web server?
- How to add BASIC Authentication into HttpURLConnection?
- How to Retrieve Multiple Result Sets from a Stored Procedure in JDBC?
- What are class variables in Java?
- What are local variables in Java?
- How to Use Updatable ResultSet in JDBC?