1

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?

rns
  • 1,047
  • 10
  • 25

2 Answers2

3

Cited from the other post:

As Everybody said in the answer that static variables are class variables. They remain in the memory until the class is not unload from JVM.

Maybe this is a dup of this one.

Community
  • 1
  • 1
facundofarias
  • 2,973
  • 28
  • 27
2

B.name is not related to any particular object: it's a class variable, and therefore it remains available as long as the class remains available (in this case, that means the lifetime of your program).

Also, it's worth noticing (even though it's not related to this particular issue) that System.gc() is a recommendation, not a guarantee that garbage collection is going to start immediately and complete before the next line in your program is executed.

Ashalynd
  • 12,363
  • 2
  • 34
  • 37