Do not Start an Executor in a static Block

Don’t do that, because  your program will hang forever.

Code, show me some code.

public class Foo{
static {
        try {
            ExecutorService executorService = Executors.newSingleThreadExecutor();
            int sum = executorService.submit(() -> {
                int x = 0;
                for (int i = 0; i<10; i++) {
                    x += i;
                return x;


        } catch (Exception e) {

  public static void main(String[]args){


This program will hang forever due to a class initialisation deadlock, both threads, the class initialisation thread and the executor thread will be waiting for the initialisation flag to be set.

Obviously the same behaviour could be reproduced with parallel streams where threads will be submitted to the ForkJoinPool behind the scenes.

static {
        Integer[]a = IntStream.range(1,50_000).boxed().toArray(Integer[]::new);
        List<Integer> filtered = Arrays.asList(a)
                .parallelStream().filter(c -> c % 2 == 0).collect(Collectors.toList());


This is not a bug, as described here it is just a stupidly written program.

Thoughts: I believe that tools (compilers/IDEs) should raise a warning about it. FindBugs spots it, because FindBugs rocks….


Leave a Reply

Name and email address are required. Your email address will not be published.

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

You may use these HTML tags and attributes:

<a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <pre> <q cite=""> <s> <strike> <strong> 

%d bloggers like this: