小编Ray*_*eng的帖子

java GC是否考虑了另一个线程中的引用?

假设定义了一个局部变量,然后传递给一个Thread构造函数,在那里它被保存为该线程的私有字段.然后,线程开始连续运行(永远,基本上),而原始方法结束.

局部变量引用已经消失,但GC是否考虑了Thread对象存储的引用?

我的方案类似于此示例代码段:

...

public static void Main(String... args) {
  Foo foo = new Foo()
  MyThread thread = new MyThread(foo)
  ExecutorService executor = Executors.newSingleThreadExecutor();
  executor.execute(thread)
}

...

public class MyThread implements Runnable {

  private Foo foo;

  public MyThread(Foo foo) {
     this.foo = foo;
  }

  public void run() {
     while (true) {
         this.foo.print(); // << throws NullPointerException
         sleep(...)
     }
  }
}
Run Code Online (Sandbox Code Playgroud)

java garbage-collection nullpointerexception

0
推荐指数
1
解决办法
60
查看次数