membersound
membersound

Reputation: 86727

How to initialize static blocks?

I have to work with a bunch of static legacy classes that contain static blocks. The classes itself are only helper classes with only static methods.

Example:

public abstract class Legacy {
    protected static final String[] ARRAY;

    static {
        //init that ARRAY
    }

    public static String convert(String value) {
        //makes use of the ARRAY variable
    }
}

Important: I don't have control over the sources and thus cannot modify the code. I know that this is a serious design flaw in how the class is build.

Problem: when accessing the class concurrently, I get exceptions from the legacy classes if the class is not initialized yet. So I have to ensure at application startup that each static class was initialized properly before.

But how could I do this?

I tried as follows:

Legacy.class.newInstance();

But that results in the following error:

java.lang.InstantiationException
    at sun.reflect.InstantiationExceptionConstructorAccessorImpl.newInstance(InstantiationExceptionConstructorAccessorImpl.java:48)
    at java.lang.reflect.Constructor.newInstance(Constructor.java:526)
    at java.lang.Class.newInstance(Class.java:374)

So probably I'm doing it wrong?

Upvotes: 0

Views: 433

Answers (2)

henry
henry

Reputation: 6096

Static initializers are thread safe in that they will only be run, and by a single thread.

They may run multiple times if the class is loaded by more than one classloader, but in that case they are effectively initializing a different class.

It is therefore unlikely that the problem you are seeing is due to incomplete initialization.

It seems more likely that your convert method is doing something that is not thread safe such as modifying the array.

Upvotes: 1

SubOptimal
SubOptimal

Reputation: 22973

If you call only static methods of the legacy classes there is no need to create an instance. The static block will be executed only once (the JVM will take care of it).

See this small example.

class Legacy {
    static {
        System.out.println("static initializer of Legacy");
    }

    public static void doSomething() {
        System.out.println("Legacy.doSomething()");
    }
}

class LegacyDemo {
    public static void main(String[] args) {
        Legacy.doSomething();
    }
}

If you run LegacyDemo it will print

static initializer of Legacy
Legacy.doSomething()

Upvotes: 0

Related Questions