java - @PreDestroy 没有被调用以用于 Runnable

标签 java multithreading spring annotations runnable

我有一个 spring 上下文,其中我们有可运行的 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类是一个抽象类,SampleRunnableX是具有原型(prototype)范围的实现,基类基本上有@PostConstruct方法和@PreDestroy方法(其主要功能是在LOCK_OBJECT上调用notify),当然一个运行方法

我的问题是调用了 PostConstruct 方法,但是当 Run 方法完成时,对象似乎没有被销毁,因此没有调用 PreDestroy 方法,并且我在 LOCK_OBJECT 上的父级中等待

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

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() 方法的末尾。

关于java - @PreDestroy 没有被调用以用于 Runnable,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31359601/

相关文章:

java - 数据库中的Android记录存在()?

java - 关于 requireEnd Matcher 方法的澄清

python - 关于多线程,Python 中的计时器如何工作?

spring - Spring JavaMailSender:使其异步且持久

java - GZIPOutputStream 与 BufferedOutputStream 的性能

java - 如何将已解析的依赖项复制到新位置,根据依赖项详细信息动态创建目录

java - 我的信号量应用程序出了什么问题?

.net - NOLOCK 与多线程

spring - 动态 Spring 特性

java - Spring - Thymeleaf 迭代