@PreDestroy 没有被 Runnable 调用

@PreDestroy not being called for a Runnable

我有一个 spring 上下文,其中我们有一个 运行nable bean 像这样启动:

public void startChildAndWait(Class type) {
  BaseMyDispatcher child = appContext.getBean(type);
  child.initialize(this); //The child references its parent during run method
  new Thread(child).start();
  synchronized(LOCK_OBJECT) {
    LOCK_OBJECT.wait(someTime);
  }
}

BaseMyDispatcher class 是一个抽象 class 和 Sample运行nableX 是具有原型范围的实现,基础 class 基本上有 @PostConstruct 方法和一个@PreDestroy 方法(其主要功能是在 LOCK_OBJECT 上调用通知)当然还有 运行 方法

我的问题是调用了 PostConstruct 方法,但是当 运行 方法完成时,对象似乎没有被销毁,因此没有调用 PreDestroy 方法,我在 LOCK_OBJECT

代码在父 运行nable 内部的函数中调用(它在 ThreadPoolExecutor 内部执行并使用相同的方法 startChildAndWait 启动(顺序)多个子级,每次传递不同的 class :

startChildAndWait(SampleRunnable1.class);
if(run2IsRequired && lastExitCode == 100) {//runIsRequired are booleans
  startChildAndWait(SampleRunnable2.class);
}
if(run3IsRequired && lastExitCode == 100) {//lastExitCode is an integer
  startChildAndWait(SampleRunnable3.class);
}

那么如何让PreDestroy方法在子线程完成时被调用呢?

来自the documentation

In contrast to the other scopes, Spring does not manage the complete lifecycle of a prototype bean: the container instantiates, configures, and otherwise assembles a prototype object, and hands it to the client, with no further record of that prototype instance. Thus, although initialization lifecycle callback methods are called on all objects regardless of scope, in the case of prototypes, configured destruction lifecycle callbacks are not called.

如果您希望在 run() 方法完成时发生某些事情,请将该代码放在 run() 方法的末尾。

@PreDestroy回调方法会在你的应用程序关闭时被调用,你需要向JVM注册一个关闭钩子并在JVM退出时关闭其中的应用程序上下文。

//Create applicationContext
final ApplicationContext appContext = 

//register ashutdown hook on application context
Runtime.getRuntime().addShutdownHook(new Thread() {
   public void run() {
       appContext.close();
   }});

如果你想在子线程完成时执行一些代码,最好把它放在运行方法(线程本身)的末尾。