1 回答

TA貢獻(xiàn)1818條經(jīng)驗(yàn) 獲得超3個贊
userSession
是對對象的引用。您“分配”null
給這個引用,而不是一個對象。所以你正在改變這個參考。它不會更改userSession
以前引用/指向的對象。
讓我試著補(bǔ)充一下:如果這個對象的方法與程序的其余部分在同一個線程中運(yùn)行,則在此方法完成后引用將被更改,因此問題甚至不會出現(xiàn)。
相反,如果這個對象在不同的線程中起作用,那么......我剛剛測試了它:
public class UnreferencedTest {
public static void main(String[] args) {
UnreferencedTest u = new UnreferencedTest();
u.createObject();
}
private void createObject() {
Unreferenced obj = new Unreferenced();
Thread t = new Thread(obj);//create new thread
t.start();
obj = null; //remove only reference to object
System.gc(); //ask GC to clean up
try {
Thread.sleep(10000); //wait a bit longer than other thread
} catch (InterruptedException e) {
e.printStackTrace();
}
}
private class Unreferenced implements Runnable {
@Override
public void run() {
try {
Thread.sleep(5000);
areYouStillHere();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
private void areYouStillHere() {
System.out.println("I'm still here!");
}
}
}
...甚至“要求” GC 清理未引用的對象。(不保證會?。┧坏却?5 秒,但仍在運(yùn)行。
希望有幫助!
添加回答
舉報(bào)