DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Related

  • MongoDB Change Streams and Go
  • Spring Application Listeners
  • What Are Events? Process, Data, and Application Integrators
  • The Pros and Cons of API-Led Connectivity

Trending

  • 5 Layers of Prompt Injection Defense You Can Wire Into Any Node.js App
  • LLM Integration in Enterprise Applications: A Practical Guide
  • Building AI-Powered Java Applications With Jakarta EE and LangChain4j
  • Getting Started With Agentic Workflows in Java and Quarkus

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.

By 
Priya Aggarwal user avatar
Priya Aggarwal
·
Jun. 05, 18 · Tutorial
Likes (7)
Comment
Save
Tweet
Share
46.4K Views

Join the DZone community and get the full member experience.

Join For Free

A 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.

Image title

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:

  1. A static member variable is set by the application (by application, I mean code outside the class containing the static block).
  2. A non-final static member variable is accessed by the application.
  3. A static method is called by the application.
  4. Class.forName(“..”).
  5. 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:

  1. An ExecutorService thread would trigger a class loading event for TcpRequestHandler.

  2. 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.'

  3. The ExecutorService thread would then acquire an 'initialization lock' on the Class TcpRequestHandler to run its static block.

  4. 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.

  5. 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.

  6. 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.

  7. 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.

  8. 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.

Blocks application Event

Published at DZone with permission of Priya Aggarwal. See the original article here.

Opinions expressed by DZone contributors are their own.

Related

  • MongoDB Change Streams and Go
  • Spring Application Listeners
  • What Are Events? Process, Data, and Application Integrators
  • The Pros and Cons of API-Led Connectivity

Partner Resources

×

Comments

The likes didn't load as expected. Please refresh the page and try again.

  • RSS
  • X
  • Facebook

ABOUT US

  • About DZone
  • Support and feedback
  • Community research

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Core Program
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 215
  • Nashville, TN 37211
  • [email protected]

Let's be friends:

  • RSS
  • X
  • Facebook