The Hidden Synchronized Keyword With a Static Block
This lesson in concurrent programming will explore static blocks, synchronization, and how to avoid deadlocks within your Java programs.
Join the DZone community and get the full member experience.
Join For FreeA static block in Java is a block of code that is executed at the time of loading a class for use in a Java application. It starts with a 'static {' and it is used for initializing static Class members in general — and is also known as a 'Static Initializer'. The most powerful use of a static block can be realized while performing operations that are required to be executed only once for a Class in an application lifecycle.
Let me provide a brief on when and how a static block is executed. A Class needs to be loaded by a ClassLoader whenever one of the following events happen:
- A static member variable is set by the application (by application, I mean code outside the class containing the static block).
- A non-final static member variable is accessed by the application.
- A static method is called by the application.
- Class.forName(“..”).
- Creating an instance using Class.newInstance() or through the new keyword.
Whenever any of those events occur, they trigger class loading activity. For creating a class instance, it must be 'fully initialized.' The JVM keeps some internal information about each class — such as Class status that tells if a Class has been loaded properly or not. For a Class to be properly loaded and get a status of 'fully initialized,' it must have all its static fields initialized and static blocks run without errors.
As the use of a static block is in the initialization/loading of a class (which should happen only once), the block is treated as a 'synchronized' block by the JVM. A thread can reach this block of code only when the class status is 'Not initialized.' Since there are multiple aforementioned events that can trigger class loading, the JVM needs to make sure that Class loading/initialization happens only once. To ensure this, there is an 'initialization lock,’ available for each class, that is acquired by the thread that reaches the static block first, and the lock is released only after the static block code execution finishes.
Other threads are blocked on any activity, like attempting class loading or creating instances, until then. Once the lock has been released, the status of the Class is set to 'fully initialized,' leaving no need for any other thread to get to the static block.
The full code to demonstrate a static initializer run blocking other threads can be seen here.
We need to be very careful when using a static initializer, though, because the class loading function depends on it — and hence so does application startup, in most cases. The code in a static block should be such that it doesn’t trigger class loading events for another class that also has a static block that, in turn, depends on this class. This may introduce the possibility of deadlock. I encountered one such incident at work where the application startup was stuck in a deadlock because of static initializers. Here, I have similar code to demonstrate the situation:
An interface, IRequestHandler, is used by a service locator to find all implementing classes on the classpath.
package com.iliyakos;
public interface IRequestHandler {
void handleRequest();
}
A class, RequestHandlerRegistrar, makes sure that all implementations of IRequestHandler are loaded:
package com.iliyakos;
import java.util.concurrent.CopyOnWriteArrayList;
public class RequestHandlerRegistrar {
private static String[] handlerNames = new String[]{"com.iliyakos.TcpRequestHandler", "com.iliyakos.UdpRequestHandler"};
private static CopyOnWriteArrayList<IRequestHandler> registeredHandlers = new CopyOnWriteArrayList<IRequestHandler>();
static {
try {
// through the service locator this class would find handler class names in real world scenario
final Class<?> aClass1 = Class.forName(handlerNames[1]);
aClass1.newInstance();
final Class<?> aClass = Class.forName(handlerNames[0]);
aClass.newInstance();
} catch (ClassNotFoundException | IllegalAccessException | InstantiationException e) {
e.printStackTrace();
}
}
public static synchronized void register(IRequestHandler handler) {
if (!registeredHandlers.contains(handler)) {
registeredHandlers.add(handler);
}
}
}
Class TcpRequestHandler provides one implementation of IRequestHandler and calls:
package com.iliyakos;
public class TcpRequestHandler implements IRequestHandler {
static {
RequestHandlerRegistrar.register(new TcpRequestHandler());
}
@Override
public void handleRequest() {
System.out.println("Handle request in TCP request handler");
}
}
Class UdpRequestHandler provides a different implementation of IRequestHandler:
package com.iliyakos;
public class UdpRequestHandler implements IRequestHandler {
static {
RequestHandlerRegistrar.register(new UdpRequestHandler());
}
@Override
public void handleRequest() {
System.out.println("Handle request in UDP request handler");
}
}
Note that the RequestHandlerRegistrar is attempting to load the classes TcpRequestHandler and UdpRequestHandler. And both implementation classes are attempting to register themselves by calling a register method in their static blocks, initializing RequestHandlerRegistrar's class loading.
This application's requirement is to have both the request handlers loaded, so the main method in the class below is trying to load the two classes:
package com.iliyakos;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
public class Main {
public static void main(String[] args) {
ExecutorService executorService = Executors.newFixedThreadPool(1);
executorService.submit(() -> {
try {
Class.forName("com.iliyakos.TcpRequestHandler").newInstance();
} catch (ClassNotFoundException | IllegalAccessException | InstantiationException e) {
e.printStackTrace();
}
}
);
try {
Class.forName("com.iliyakos.UdpRequestHandler").newInstance();
} catch (ClassNotFoundException | IllegalAccessException | InstantiationException e) {
e.printStackTrace();
}
executorService.shutdown();
}
}
This results in a deadlock. Here are the series of steps that would take place:
An ExecutorService thread would trigger a class loading event for TcpRequestHandler.
The ExecutorService thread would start by checking if the class has a 'fully initialized' state. Because it is not loaded yet, the state would instead be 'Not initialized.'
The ExecutorService thread would then acquire an 'initialization lock' on the Class TcpRequestHandler to run its static block.
The main thread would trigger a class loading event of UdpRequestHandler, and then acquire an 'initialization lock' followed by starting the execution of its static block.
The static block in TcPRequestHandler will trigger a class loading event of the RequestHandlerRegistrar class. The ExecutorService thread will then acquire an 'initialization lock' of the Class RequestHandlerRegistrar to execute its static block.
To execute a static method of RequestHandlerRegistrar in a static block of UdpRequestHandler, the main thread would wait to acquire the 'initialization lock' of the RequestHandlerRegistrar, since the class is not loaded yet.
The static block in RequestHandlerRegistrar will again trigger the class loading event of TcpRequestHandler, and the ExecutorService thread will check the state of the class, which is still 'Not initialized,' but it won't be blocked.
The ExecutorService thread would then execute the statement of loading UdpRequestHandler from the static block of RequestHandlerRegistrar. The UdpRequestHandler is not loaded yet, but the 'initialization lock' has been acquired by the main thread.
While the main thread is waiting on initialization to complete for the RequestHandlerRegistrar event (started by the ExecutorService thread — it is still in its static block), the ExecutorService thread is waiting on the UdpRequestHandler initialization completion event — the static block of which is under execution by the main thread, creating a deadlock situation.
Full code to demonstrate how a static initializer in conjuction with a ServiceLocator can cause a deadlock can be seen here.
Published at DZone with permission of Priya Aggarwal. See the original article here.
Opinions expressed by DZone contributors are their own.
Comments