What is the use of static synchronized method in java?
In general, synchronized
methods are used to protect access to resources that are accessed concurrently. When a resource that is being accessed concurrently belongs to each instance of your class, you use a synchronized
instance method; when the resource belongs to all instances (i.e. when it is in a static
variable) then you use a synchronized static
method to access it.
For example, you could make a static
factory method that keeps a "registry" of all objects that it has produced. A natural place for such registry would be a static
collection. If your factory is used from multiple threads, you need to make the factory method synchronized
(or have a synchronized
block inside the method) to protect access to the shared static
collection.
Note that using synchronized
without a specific lock object is generally not the safest choice when you are building a library to be used in code written by others. This is because malicious code could synchronize on your object or a class to block your own methods from executing. To protect your code against this, create a private "lock" object, instance or static, and synchronize on that object instead.
At run time every loaded class has an instance of a Class
object. That is the object that is used as the shared lock object by static synchronized
methods. (Any synchronized method or block has to lock on some shared object.)
You can also synchronize on this object manually if wanted (whether in a static method or not). These three methods behave the same, allowing only one thread at a time into the inner block:
class Foo {
static synchronized void methodA() {
// ...
}
static void methodB() {
synchronized (Foo.class) {
// ...
}
}
static void methodC() {
Object lock = Foo.class;
synchronized (lock) {
// ...
}
}
}
The intended purpose of static synchronized
methods is when you want to allow only one thread at a time to use some mutable state stored in static
variables of a class.
Nowadays, Java has more powerful concurrency features, in java.util.concurrent
and its subpackages, but the core Java 1.0 constructs such as synchronized
methods are still valid and usable.