What happens when java program starts?

Recently have been touched Java classloaders and suddenly recognized that do not fully understand what happens step-by-step when someone calls

java -jar App.jar

Well I guess

  • a new instance of JVM is created
  • it uses ClassLoader to load main class and other classes
  • byte-code is started to execute from main() method
  • But still I suppose there are many things I need to know more about it.

  • Who and how decides which classes should be loaded at startup and which once needed?
  • I have found two related questions but there it is not explained how to apply that to Java realities.

    What happens when a computer program runs?

    What happens when you run a program?


    •Who and how decides which classes should be loaded at startup and which once needed?

    we need to understand the fundamentals of java class loading. Initially bootstrap classloader (it is implemented natively as part of the VM itself) is responsible for loading core system classes. Then there are other class loaders as well like Extension, system, user-defined(optional) class loaders which decide when and how classes should be loaded. Fundamentals of class loading


    The decision is made by the classloader. There are different implementations, some of which pre-load all classes they can and some only loading classes as they are needed.

    A class only needs to be loaded when it is accessed from the program code for the first time; this access may be the instantiation of an object from that class or access to one of its static members. Usually, the default classloader will lazily load classes when they are needed.

    Some classes cannot be relied on to be pre-loaded in any case however: Classes accessed via Class.forName(...) may not be determined until this code is actually exectued.

    Among other options, for simple experiments, you can use static initializer code to have a look at the actual time and order in which classes are actually loaded; this code will be executed when the class is loaded for the first time; example:

    class SomeClass {
    
        static {
            System.out.println("Class SomeClass was initialized.");
        }
    
        public SomeClass() {
            ...
        }
    
        ...
    
    }
    

    Your example shows an executable jar, which is simply a normal java archive (jar) with an extra key/value pair in it's manifest file (located in folder "META_INF" ). The key is " Main-Class " and the value the fully qualified classname of that class whose "main" method will be executed, if you "run" the jar just like in your example.

    A jar is a zip file and you can have a look inside with every zip archive tool.

    链接地址: http://www.djcxy.com/p/11608.html

    上一篇: ZF2模块加载性能

    下一篇: 当java程序启动时会发生什么?