javamultithreadingconcurrencystaticsafe-publication

Are static blocks executed in sequential order? Also what if it isn't a block


Are these lines with static initializers guaranteed to run in order? Because if not then things might go wrong

public Class x {
    private static final BasicDataSource ds = new BasicDataSource();
    private static final JdbcTemplate jdbcTemplate = new JdbcTemplate(ds);
    private static final SomeDao someDao = new SomeDao(jdbcTemplate);
}

Okay... How about this?

public Class x {
    private static final BasicDataSource ds;
    private static final JdbcTemplate jdbcTemplate;
    private static final SomeDao someDao;

    static {
        ds = new BasicDataSource();
        ds.setStuff("foo");
        ds.setAnotherProperty("bar");
        jdbcTemplate = new JdbcTemplate(ds);
        SomeDao someDao = new SomeDao(jdbcTemplate);
    }
}

Solution

  • They will be executed in sequential order corresponding to how they were listed in the source code.

    A class can have any number of static initialization blocks, and they can appear anywhere in the class body. The runtime system guarantees that static initialization blocks are called in the order that they appear in the source code. Initializing Fields

    This can be observed using in the following code:

    private static A a1 = new A(0);
    private static A a2 = new A(1);
    private static A a3 = new A(2);
    private static A a4 = new A(3);
    private static A a5 = new A(4);
    private static A a6 = new A(5);
    
    public static void main (String args[]) {  }
    
    static class A {
        public A (int a) {
            System.out.print(a);
        }
    }
    

    For which the output is always 012345.