0

I encountered a strange problem while using ExecutorService to execute a Callable in static block. let's see the complete code directly as below.

package com.acme;

import java.util.concurrent.Callable;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;

public class App {
   private static int data = 0;

   static {
       ExecutorService executor = Executors.newFixedThreadPool(1);
       Future<String> future = executor.submit(new Callable<String>() {
           @Override
           public String call() throws Exception {
               System.out.println("" + data);
               return "hello";
           }
       });       
     }

  public static void main(String[] args) {
    System.out.println("enter main scope");
  }
 }

Run the main method, the result is presented as below screenshot.

enter image description here

However, if I add some business code as below, nothing is printed in the console.

 public class App {
   private static int data = 0;

   static {
       ExecutorService executor = Executors.newFixedThreadPool(1);
       Future<String> future = executor.submit(new Callable<String>() {
           @Override
           public String call() throws Exception {
               System.out.println("" + data);
               return "hello";
           }
       });    

      try {
          future.get();
      } catch (InterruptedException e) {
          e.printStackTrace();
      } catch (ExecutionException e) {
          e.printStackTrace();
      }   
  }

  public static void main(String[] args) {
    System.out.println("enter main scope");
  }
 }

Anyone can provide some help about this issue? more details are preciated.

Sunny
  • 129
  • 1
  • 3

1 Answers1

0

As you made executor code run in static block which force the code to run even before App.class context is full created (i.e class not fully loaded in memory or you can say now "data" variable is not in memory ).

Basically when your call method get called through executor its(thread) trying to find the variable "data" in App.class but it might not be loaded till now, this is also making thread run infinite.

Solution :

  1. Run the executor in main block but still there is a issue ,suppose if for some reason (business logic) the App.class get unloaded you will be again stuck with a infinitely running thread that is finding "data".

  2. Make the data variable "final", then you can put your code either is static block or static method (Ex. main). As for final variable a separate copy is maintained and has issue of class loading or unloading above issue will not come.

Sachin
  • 176
  • 1
  • 11