即使 ExecutorService 受到 isShutdown() 保护,也会出现 RejectedExecutionException
我有一个问题让我抓狂了一段时间,我需要咨询你们的集体智慧。
我有一个线程池为 1 的 ThreadPoolExecutor,从 Executors.newFixedThreadPool 调用。我用 !isShutdown() 保护所有 executor.execute() ,因为 executor.shutdown() 是从另一个线程调用的,因此应该能够说执行器不会抛出 RejectedExecutionException。然而,这是我随机看到的。
有谁知道为什么我会看到这种行为?
I've got a problem that's been driving me nuts for a while and I need to consult your collective wisdom.
I have a ThreadPoolExecutor with a pool of 1, called from Executors.newFixedThreadPool. I guard all executor.execute() with !isShutdown() since executor.shutdown() is called from another thread, and so should be able to say that the executor will not throw a RejectedExecutionException. Nevertheless, this is what I'm seeing randomly.
Does anyone have a good idea why I'm seeing this behaviour?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您可能会阅读一篇关于双重检查锁定的文章为了理解不同步的“if then act”方法如何/为什么在 java 中不起作用。
出于好奇,你为什么要费力去检查作品是否会被拒绝呢?我不记得以前见过这样的事。相反,为什么不捕获并处理抛出的任何 RejectedExecutionException?
还要注意如何处理其他错误情况,尤其是在调用关闭时正在运行或在队列中等待的任务。 《Java 并发实践》的第 7 章有很多关于这方面的好信息。
You might go through an article on double-checked locking in order to understand how/why an unsynchronized "if then act" approach doesn't work in java.
Out of curiosity, why do you bother to check if the work will be rejected? I can't remember seeing this done before. Instead, why not catch and handle any RejectedExecutionExceptions that are thrown?
Also be careful of how you're handling other error conditions, especially tasks that are running or waiting in the queue when shutdown is called. Chapter 7 of Java Concurrency in Practice has lots of good information about this.
此处列出了拒绝执行的其他原因 http://download.oracle.com/javase/1,5.0/docs/api/java/util/concurrent/ThreadPoolExecutor.html
很可能您的队列已达到其界限。
There are other reasons for rejected execution that are spelled out here http://download.oracle.com/javase/1,5.0/docs/api/java/util/concurrent/ThreadPoolExecutor.html
Most likely your queue reached it's bounds.