谁能解释一下为什么在分离的线程中执行countDown时,await方法上的CountDownLatch挂起了?这个测试永远不会结束,有趣的是,在我想执行countDown方法的地方,ThreadPoolTaskExecutor不会执行代码。我确信ThreadPoolTaskExecutor会在不同的线程中执行回调,CountDownLatch::await会被释放。
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
...
private ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
@Test
void nestedInitialization() {
executor.initialize();
var beanInitializer = new Initializer(executor);
beanInitializer.initialize(() -> {
new SomeBean().init();
});
sleep(150);
assertEquals(0, executor.getThreadPoolExecutor().getQueue().size());
assertTrue(beanInitializer.isInitializationDone());
}
class SomeBean {
private AnotherBean anotherBean = new AnotherBean();
void init() {
anotherBean.init();
}
}
class AnotherBean {
private final Initializer initializer = new Initializer(executor);
void init() {
initializer.initialize(this::internalInit);
}
void internalInit() {
sleep(100);
}
}
public class Initializer {
private ThreadPoolTaskExecutor bootstrapExecutor;
private final CountDownLatch countDownLatch = new CountDownLatch(2);
private Initializer(ThreadPoolTaskExecutor bootstrapExecutor) {
this.bootstrapExecutor = bootstrapExecutor;
}
public void initialize(Runnable callback) {
synchronized (this) {
if (isNotInitialized()) {
countDownLatch.countDown(); // set 1 in latch
bootstrapExecutor.execute(() -> {
callback.run();
countDownLatch.countDown(); // <-- this doesn't execute
});
}
}
if (initializationStarted()) {
try {
countDownLatch.await();
}
catch (InterruptedException e) {
e.printStackTrace();
}
}
}
boolean isNotInitialized() { return countDownLatch.getCount() == 2; }
boolean initializationStarted() { return countDownLatch.getCount() == 1; }
boolean isInitializationDone() { return countDownLatch.getCount() == 0; }
}如果我在await方法中设置了任何超时,任务执行器中的回调将在超时和测试通过后执行……我不能理解这一点。
发布于 2021-07-23 16:18:59
问题出在池的大小上。默认情况下,ThreadPoolTaskExecutor池中只有一个线程。我增加了corePolSize,现在他的代码可以工作了。谢谢安德烈亚斯!
https://stackoverflow.com/questions/68489648
复制相似问题