Search code examples
javaspring-bootobjectconnectionjavers

Why does code in static block execute multiple times?


I have created a class in Spring boot to establish a global javers object that can be used by all classes. This is my code.

@Component
public class JaversInstance {

    public static final Javers javers;
    static
    {

        ConnectionProvider connectionProvider = new ConnectionProvider() {
            @Override
            public Connection getConnection() throws SQLException {
                String url = "any_url";
                Properties props = new Properties();
                props.setProperty("user", "test");
                props.setProperty("password", "test");
                DriverManager.getConnection(url, props);
                System.out.println("CONNECTION PROVIDER invoked");
                return DriverManager.getConnection(url, props);
            }
        };

        JaversSqlRepository sqlRepository = SqlRepositoryBuilder
                .sqlRepository()
                .withConnectionProvider(connectionProvider)
                .withDialect(DialectName.MYSQL).build();
        System.out.println("JAVERS instance creation");
        javers = JaversBuilder.javers().registerJaversRepository(sqlRepository).build();
    }

    private JaversInstance() {

    }

}

Output:

JAVERS instance creation
CONNECTION PROVIDER invoked
CONNECTION PROVIDER invoked
CONNECTION PROVIDER invoked
CONNECTION PROVIDER invoked
CONNECTION PROVIDER invoked
CONNECTION PROVIDER invoked
CONNECTION PROVIDER invoked
CONNECTION PROVIDER invoked
CONNECTION PROVIDER invoked

Can someone tell me what has happened here. Why the getConnection() is called so many times? Is this any kind of retry?


Solution

  • It happens as many times as the anonymous class of ConnectionProvider is loaded. The following code will help you understand it better:

    import java.util.ArrayList;
    import java.util.Collections;
    import java.util.Comparator;
    import java.util.List;
    
    public class Main {
        static Comparator<Integer> comparator;
        static {
            comparator = new Comparator() {
                @Override
                public int compare(Object o1, Object o2) {
                    System.out.println("Hello");
                    return 0;
                }
            };
        }
    
        public static void main(String[] args) {
            List<Integer> list = new ArrayList<Integer>();
            list.add(40);
            list.add(20);
            list.add(10);
            list.add(30);
            Collections.sort(list, comparator);
        }
    }
    

    Output:

    Hello
    Hello
    Hello