Following is my Program for testing life of static variables.
public class A {
public static void main(String[] args) throws InterruptedException {
Thread thread = new Thread(new B());
thread.start();
while(thread.isAlive()){
Thread.sleep(1000);
}
System.gc();
Thread thread2 = new Thread(new B());
thread2.start();
while(thread2.isAlive()){
Thread.sleep(1000);
}
System.gc();
System.out.println("Last One :: " + B.name);
}
}
B.java
public class B implements Runnable{
public static int name;
@Override
protected void finalize() throws Throwable {
super.finalize();
System.out.println("Finalize called");
}
@Override
public void run() {
for(int i=0;i<10;i++){
name++;
}
System.out.println("Class B :: " + name);
}
}
Output:
Class B :: 10
Finalize called
Class B :: 20
Finalize called
Last One :: 20
The first thread creates new instance of B,starts the thread increment pointer of name variable and the main-thread waits till the thread completes and calls GC.Again i repeat the process,Still the old pointer is maintained even after the thread creating instance of B is completed and GC is runned 2 times.How static variables are stored in memory and how long they they are maintained in memory?