Reputation: 863
When a program written in Java is running, will all of its classes be all loaded into the main memory? If so, isn't it a waste of RAM?
Upvotes: 3
Views: 107
Reputation: 29139
Only classes that are referenced during a particular execution are loaded. Most large Java programs will frequently run with many of the classes not loaded as those classes serve various scenarios not exercised by that particular process.
Classes in the standard library are handled the same as application classes. For instance, if your application does not reference AWT, no classes in AWT packages will be loaded.
Java language spec contains the wording which explicitly precludes eager initialization of classes.
A class or interface type T will be initialized immediately before the first occurrence of any one of the following:
- T is a class and an instance of T is created.
- T is a class and a static method declared by T is invoked.
- A static field declared by T is assigned.
- A static field declared by T is used and the field is not a constant variable (§4.12.4).
- T is a top-level class, and an assert statement (§14.10) lexically nested
Note my use of the term "initialization". A class is initialized as part of constructing Class object, when parsing the binary data that defines the class.
There is nothing precluding a particular ClassLoader implementation from loading the binaries of all the classes that it sees into memory, but it cannot fully load those classes until they are requested without violating JLS.
For a common ClassLoader implementation, see URLClassLoader.
Upvotes: 2
Reputation: 47609
No it's fine, because of virtual address space and virtual memory. Read these:
http://en.wikipedia.org/wiki/Virtual_memory
http://en.wikipedia.org/wiki/Virtual_address_space
Virtual memory means that you can load a large amount into memory and the unused sections are saved to disc and are moved out of physical RAM.
Virtual address space means that each process (one example of a process is your Java program) has its own address space, so it does not 'steal' addresses from other processes.
Upvotes: 6