1

If I have a java class like below

public class XXX {
  static {
  ...
  ...
  }
}

And if the JVM ( because of GC triggered by Permgen ) unloads the class and loads it later again, will the static block get called twice?

Sony Antony
  • 314
  • 1
  • 11

4 Answers4

2

Quoting from this other post: https://stackoverflow.com/a/148707/641955

The only way that a Class can be unloaded is if the Classloader used is garbage collected. This means, references to every single class and to the classloader itself need to go the way of the dodo.

If that's what you're doing, then yes, the static block will get executed twice during the lifetime of your program, once each for the lifetime of each classloader.

Community
  • 1
  • 1
janos
  • 120,954
  • 29
  • 226
  • 236
0

Yes. You could also use different class loaders to load the class multiple times and the static block would be called for each load.

Kayaman
  • 72,141
  • 5
  • 83
  • 121
0

When JVM loads a class it stays loaded and class definitions are held in the PermGen memory pool for this reason.

However, it is possible for the class' bytecode to be loaded by multiple classloaders, and each time this happens the static block will be executed again as this is a new class. Each class is only visible within the scope of its own classloader.

And if the JVM ( because of GC triggered by Permgen ) unloads the class and loads it later again, will teh static block get called twice ?

Yes it should.

akhil_mittal
  • 23,309
  • 7
  • 96
  • 95
  • Thanks @janos. I got mislead into believing that the classes can get unloaded, because I was seeing a whole lot of 'Unloading..' statements in teh console logs of JVMs struggling for memory – Sony Antony Oct 04 '15 at 16:00
0

The static initializer is executed only once per ClassLoader.

For a exhaustinc explanation have a look into section JLS 12.4.2
"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 (§7.6), and an assert statement (§14.10) lexically nested 
within T (§8.1.3) is executed.
SubOptimal
  • 22,518
  • 3
  • 53
  • 69