Is there a way to kill a child thread after some specified time limit in Java? Edit: Also this particular thread may be blocked in its worst case (Thread is used to wait for a file modification and blocks until this event occurs), so im not sure that interrupt() will be successful?
相关问题
- Delete Messages from a Topic in Apache Kafka
- Jackson Deserialization not calling deserialize on
- How to maintain order of key-value in DataFrame sa
- StackExchange API - Deserialize Date in JSON Respo
- Difference between Types.INTEGER and Types.NULL in
You can use AOP and a
@Timeable
annotation for your method from jcabi-aspects (I'm a developer):When time limit is reached your thread will get
interrupted()
flag set totrue
and it's your job to handle this situation correctly and to stop execution. Normally it's done byThread.sleep(..)
.Some helpful changes were introduced as part of JEP 266 in
CompletableFuture
since Java 9. Using orTimeout method, for now, it is possible to write it like:In Java 8, unfortunately, you should use some extra code. Here is an example of delegation pattern usage with help of Lombok:
Of course, the code above easily could be rewritten as just a static factory method:
Make use of
ExecutorService
to execute theCallable
, checkout the methods wherein you can specify the timeout. E.g.Here
Task
of course implementsCallable
.Brian's right, interrupting it is safer than "stopping" the thread.
What if the thread is locking on an object mid-modification, and suddenly gets stopped (which causes the lock to be released)? You get weird results.
Do not use
destroy()
since that does not perform any cleanup.The most straightforward way is to use
join()
, likeYou could use an
ExecutorService
. That would make a lot of sense if you have several threads running concurrently. If you have the need to spawn new threads while other threads are running, you can combine this with aBlockingQueue
.A
ThreadPoolExecutor
(anExecutorService
-implementation) can take aBlockingQueue
as argument, and you can simply add new threads to the queue. When you are done you simply terminate theThreadPoolExecutor
.You can keep a count of all the threads added to the queue. When you think you are done (the queue is empty, perhaps?) simply compare this to
If the two match, you are done. Another way to terminate the pool is to wait a second in a loop:
Why not
interrupt()
it after a particular time ? Your spawned thread will have to be able to handle anInterruptedException
properly.See this article (http://www.javaspecialists.eu/archive/Issue056.html) for more information on shutting down threads cleanly.
See also the Executor/Future framework, which provide useful methods for collecting results and/or terminating threads within particular time limits.