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