How to run an initializer method in Java when JVM starts?

java init method example
3 ways to initialize object in java
object initialization in java
java class initialization order
java initialize instance variables outside constructor
variable initialization in java
java initializer block
java variable initialization best practices

I am building a Java library of a few Java, Maven projects. There is no main method in any of the projects since it is a library. In web applications, you can create a class that implements ServletContextListener and it will execute when your server starts (e.g. when Tomcat starts). I want to do the same, but for the library (which is not a web application or a console application. It is just a reusable library). If someone writes a program that uses my library, I want my initialzer class to execute when the JVM starts in order to do some initialization I want it to do. How could I do that?

Thank you

You want specific initialization code always to be executed at first, before a (Java) library is being used.

The J2EE/Spring option using @PostConstruct has already been addressed for the question posed. Using Java SE, you can encapsulate your Java library by a singleton class - a class which is the 'entrance' to the rest of the functionality of your library.

The constructor of the singleton class can call all necessary initialization code, before passing control back to the caller (the main web-application).

public class LibraryInstance {

    private FunctionalClass1 functionalClass1;
    private FunctionalClass2 functionalClass2;
    ...

    private LibraryInstance() { runInitializingCode(); }
    private static final LibraryInstance instance = new LibraryInstance();
    public static LibraryInstance getInstance() {
        return instance;
    }

    private void runInitializingCode() { 
        ....
    }
}

Should work out-of-the-box.

Class and object initialization in Java, Learn how to to initialize Java classes and objects for successful JVM execution. Learn Java from beginning concepts to advanced design patterns in this sine and cosine values, by calling the Math class's sin() and cos() methods. As per Java 8 Virtual Machine Specification, it is the process of taking a class or interface and combining it into the run-time state of the JVM so that it can be executed. The linking begins with the process of verification of the class, ensuring that it adheres to the semantics of the language and does not disrupt the integrity of JVM.

When and how a Java class is loaded and initialized?, Java is capable of loading classes at run time. The confusion. at run time. The confusion is what is the difference between "load" and "initialize". The linking-​like step for Java is done when they are loaded into JVM. Different package compiler; public class A { public void method(){ System.out.println("inside of A"); } }  An initializer is a line of code (or a block of code) placed outside any method, constructor, or other block of code. Initializers are executed whenever an instance of a class is created, regardless of which constructor is used to create the instance. The simplest initializers are those that declare and initialize fields. For example: […]

If you add a JAR as a -javaagent: on the command line, a premain method will be called before the main of the program you are running.

e.g.

import java.lang.instrument.Instrumentation;

public class Agent {
  public static void premain(String args, Instrumentation instrumentation){
    // early initalization
  }
}

https://zeroturnaround.com/rebellabs/how-to-inspect-classes-in-your-jvm/

What Is an Initializer in Java?, Which method signature is recognized as the entry point for Java programs? When an RPG program calls a Java method using the RPG EXTPROC(*JAVA) support, the RPG runtime determines if there is already a JVM active in the job. If there is, it just attaches to the current JVM to make the method call. If there is no JVM yet, the RPG runtime starts the JVM.

public static void main(String[] args) - Java main method, . Its syntax is always public static void main(String[] args) . You can only change the name of String array argument, for example you can change args to myStringArgs . Also String array argument can be written as String When writing code that initializes different types of fields, of course, we have to keep an eye on the order of initialization. In Java, the order for initialization statements is as follows: static variables and static initializers in order. instance variables and instance initializers in order.

Understand JVM Loading, JVM Linking, and JVM Initialization, for execution. Other processes—such as instantiation, garbage collection, and finalization—occur at the middle stages of the lifetime of the class life cycle. JVM will initialize superclass and fields in textual order, initialize static, final fields first, and give every field a default value before initialization. Java Class Instance Initialization is an example that shows the order of execution for field, static field and constructor.

A Guide to Java Initialization, Simply put, before we can work with an object on the JVM, it has to be initialized. Let's start by making sure that we're on the same page. Now we can use our constructor to create a User object with initial values for its  The start () method internally calls the run () method of Runnable interface to execute the code specified in the run () method in a separate thread. The thread moves from New State to Runnable state. When the thread gets a chance to execute, its target run () method will run.

Comments
  • Normally you simply add your library to any java project and import the class you are willing to use. If you want your initializer class to execute then call it in the main method of your other java program.
  • Is it absolutely necessary for you initializer to run when the JVM starts, or does it just have to run before any of the library code is used? The first cannot be done without adding code to the main code using the library. The second is common and is called lazy initialization, i.e. the initialization is deferred until needed.
  • What sort of initialization? Depending on what it is, it might be possible to just put static blocks in the classes that rely on said initialization. Or it might be necessary to communicate to future users, via the documentation, that some pre-configuration is necessary before using the library. It really depends on what sort of initialization we're talking about.
  • This sort of sounds like an X-Y problem and also something a library shouldn't perhaps be doing.
  • @DimitriosEfthymiou Then look at the link I gave earlier, or search the web for lazy initialization. If you need your configuration registry to be initialized from property file before it is used, it should probably be the registry that auto-initializes itself lazily when first accessed, e.g. in a static initializer block.
  • so, essentially you are suggesting I should create an API gateway or a facade for each project. I want to use the initialisation code so that I can register properties from prop files to the configuration registry at the very beginning, right before the JVM finishes its startup/initialisation. So, the question is how can I register the props from the prop files (that exist in src/main/resources) when the JVM starts?
  • You can add a @PostConstruct-annotated method to your main web-application. That method can read the properties you mention and subsequently call LibraryInstance (possibly passing the relevant subset of parameters - not shown in my code example above), in order to instantiate the library during JVM-startup.
  • I am not using Spring Beans. A static block would be perfect, but unfortunately it executes when someone uses the class for the first time (lazy-init) and not when the classloader is working at the JVM startup. I want to use the initialisation code so that I can register a few properties from prop files to the configuration registry at the very beginning, right before the JVM finishes its startup/initialisation, i.e. before anyone makes a call to teh library. So, the question is how can I register the props from the prop files (that exist in src/main/resources) when the JVM starts?
  • Static block will initialise at class load time and not when a user first accesses a class method, so this might be a good option. Other than that, if you’re asking a user to edit a property file then it makes sense (to me) to also ask them to call an initialisation method in order to use your library.
  • I still don't get the "right before the JVM finishes its startup/initialisation" bit. It is not possible to invoke a method a method, static or not, on a class, without the static block being executed first. You're focussing on the exact point of execution and it just doesn't make sense, to me at least.