سؤال

Why below System.exit(0) is called in below program? It should be called only when map reference variable becomes null.

import java.lang.ref.WeakReference; 
import java.util.HashMap; 
import java.util.Map; 
public class ReferencesTest { 
    private WeakReference<Map<Integer, String>> myMap; 
    public static void main(String[] args) { 
        new ReferencesTest().doFunction(); 
    } 

    private void doFunction() { 
        Map<Integer, String> map = new HashMap<Integer, String>(); 
        myMap = new WeakReference<Map<Integer, String>>(map); 
        int i = 0; 
        while (true) { 
            if (myMap != null && myMap.get() != null) { 
                myMap.get().put(i++, "test" + i);
                System.out.println("im still working!!!!"+i+" Map Size"+myMap.get().size()); 
                System.gc();
            } else { 
                System.out 
                .println("*******im free*******"); 
                System.exit(0);
            } 
        } 
    } 
}

Last few lines of Output are

im still working!!!!15586 Map Size15586
im still working!!!!15587 Map Size15587
im still working!!!!15588 Map Size15588
*******im free*******
هل كانت مفيدة؟

المحلول

THE VARIABLE map is not used (not referenced) anywhere inside the while cycle (or further down). Just because the variable is still in scope, as seen in source; or the fact that it does have a designated local variable entry in the method's bytecode does not mean that THE VARIABLE map is actually in scope DURING RUNTIME, especially after JIT compilation.

Unless you compile with an option to explicitly keep unused local variables (in their whole scope), this is the expected behavior.

Proof (--XX:+PrintCompilation):

im still working!!!!15586 Map Size15586
im still working!!!!15587 Map Size15587
im still working!!!!15588 Map Size15588
 259509   23 %           eu.revengineer.sync.ReferencesTest::doFunction @ -2 (144 bytes)   made not entrant
*******im free*******

نصائح أخرى

I suppose what you actually want to use is the WeakHashMap (http://docs.oracle.com/javase/6/docs/api/java/util/WeakHashMap.html).

A weak reference to a HashMap will be removed under memory pressure, rendering your whole map unreachable and even terminating the program in your case. WeakHashMap uses weak references to its keys instead so only the map will lose (key, value) pairs under memory pressure.

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top