Uploaded image for project: 'JDK'
  1. JDK
  2. JDK-8281371

Deadlock in lambda expression when used as static initializer in class constructor

XMLWordPrintable

    • generic
    • generic

      ADDITIONAL SYSTEM INFORMATION :
      Oracle JDK 17.0.2 / Windows10 x64

      A DESCRIPTION OF THE PROBLEM :
      Looks like a strange behavior of lambda expression used as static initializer into class constructor, causing a unexpected execution deadlock

      STEPS TO FOLLOW TO REPRODUCE THE PROBLEM :
      Just execute the code

      EXPECTED VERSUS ACTUAL BEHAVIOR :
      EXPECTED -
      It should initialize the class and print results
      ACTUAL -
      deadlock in constructor

      ---------- BEGIN SOURCE ----------
      /*
       * Created on Jan 26, 2022
       */
      package test;

      /**
       * @author dar
       */
      public class StaticFieldsTest
      {
      private static final String VALUE = "10";
      private static final StaticFieldsTest sharedInstance = new StaticFieldsTest();

      /**
      *
      */
      public StaticFieldsTest()
      {
      System.out.println("---------- start -----------");

      // here we create our initializer
      final Thread t = new Thread(() ->
      {
      System.out.println("inside runnable");
      System.out.println("value is " + VALUE);

      // uncomment this line to prevent DEADLOCK
      // initialize();
      });

      // execute!
      t.start();

      try
      {
      // wait completion
      t.join();
      }
      catch (InterruptedException e)
      {
      e.printStackTrace();
      }

      System.out.println("----------- end ------------");
      }

      /**
      * a do-nothing method
      */
      private void initialize()
      {
      // do nothing
      }

      /**
      * @param args String[]
      */
      public static void main(final String[] args)
      {
      StaticFieldsTest test = StaticFieldsTest.sharedInstance;
      System.exit(0);
      }
      }
      ---------- END SOURCE ----------

      CUSTOMER SUBMITTED WORKAROUND :
      Look at the source:

      just uncomment a do-nothing initialize(); call

      // uncomment this line to prevent DEADLOCK
      // initialize();


      FREQUENCY : always


            vromero Vicente Arturo Romero Zaldivar
            webbuggrp Webbug Group
            Votes:
            0 Vote for this issue
            Watchers:
            5 Start watching this issue

              Created:
              Updated:
              Resolved: