这个问题发布在某个网站上.我没有在那里找到正确的答案,所以我再次在这里发布.
public class TestThread {
public static void main(String[] s) {
// anonymous class extends Thread
Thread t = new Thread() {
public void run() {
// infinite loop
while (true) {
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
}
// as long as this line printed out, you know it is alive.
System.out.println("thread is running...");
}
}
};
t.start(); // Line A
t = null; // Line B
// no more references for Thread t
// another infinite …Run Code Online (Sandbox Code Playgroud) 我想避免(大多数)Netbeans 6.9.1的警告,我的'Leaking this in constructor'警告有问题.
我理解这个问题,在构造函数中调用一个方法并传递" this"是危险的,因为" this"可能没有完全初始化.
很容易在我的单例类中修复警告,因为构造函数是私有的,只能从同一个类中调用.
旧代码(简化):
private Singleton() {
...
addWindowFocusListener(this);
}
public static Singleton getInstance() {
...
instance = new Singleton();
...
}
Run Code Online (Sandbox Code Playgroud)
新代码(简化):
private Singleton() {
...
}
public static Singleton getInstance() {
...
instance = new Singleton();
addWindowFocusListener( instance );
...
}
Run Code Online (Sandbox Code Playgroud)
如果构造函数是公共的并且可以从其他类调用,则此修复不起作用.如何修复以下代码:
public class MyClass {
...
List<MyClass> instances = new ArrayList<MyClass>();
...
public MyClass() {
...
instances.add(this);
}
}
Run Code Online (Sandbox Code Playgroud)
当然我想要一个修复,它不需要使用这个类修改我的所有代码(例如通过调用init方法).
Goetz的Java Concurrency in Practice,第41页提到了this在构造过程中引用如何逃脱.一个"不要这样做"的例子:
public class ThisEscape {
public ThisEscape(EventSource source) {
source.registerListener(
new EventListener() {
public void onEvent(Event e) {
doSomething(e);
}
});
}
}
Run Code Online (Sandbox Code Playgroud)
这this是通过doSomething(e)引用封闭ThisEscape实例的事实"逃避" .可以通过使用静态工厂方法(首先构造普通对象,然后注册侦听器)而不是公共构造函数(完成所有工作)来解决这种情况.这本书继续:
从构造函数中发布对象可以发布未完全构造的对象.这是真实的,即使是公布在构造函数中的最后一条语句.如果
this参考在构造期间逃逸,则认为该对象未正确构造.
我不太懂.如果发布是构造函数中的最后一个语句,那么之前没有完成所有构建工作吗?怎么会是this由当时不是有效?显然有一些伏都教在那之后继续,但是什么?