I am running a fixed amount of threads using newFixedThreadPool() and need to be able to
know when one of the runnables has died, and
know which specific runnable was the one that died.
One solution for this was by wrapping the Runnables with as a Thread object and calling on isAlive(). The Threads ran as they should have, but since aThread.start() was never called by the executor always returned false which is of no use to me. I considered the possibility of having the Runnables trigger a flag at the beginning of the run() function just like this question's answer suggested. What would be the best way to keep track of the Runnables that have died? Because my intention is to submit a thread to the executor that that would essentially do the same thing as the one that died.
After looking at the documentation that #vk3105 provided I had an idea. I ended up looking at this and implemented Future future = executorService.submit(aRunnable) so that i can check if that runnable was terminated or not by using future.isDone() or if the Runnable was cancelled before it was completed future.isCancelled().
Maybe you can you use Thread.getState().
And here is a state diagram for threads. http://bighai.com/ppjava/?p=144
http://docs.oracle.com/javase/1.5.0/docs/api/java/lang/Thread.html#getState()
http://docs.oracle.com/javase/1.5.0/docs/api/java/lang/Thread.State.html
Related
I need to block execution of a thread until resumed from another thread. So I wrote my own implementation using wait() method. Which seems to be working, but it is far from simple.
Is there any ready to use solution? Preferably in java SE 6? Or do I have to use my own implementation? I couldn't find any.
Update
More specifically. I need work->block->external release->work->end behavior from thread 1 and ability to release block from thread 2.
have a a look at the classes in java.util.conucurrent ...
CountDownLatch might be a solution for your problem if i understand your problem correctly.
I need to block execution of a thread until resumed from another thread.
Not enough information. Do you need an on/off switch that is controlled entirely by one thread and obeyed by the other? That might be a good application for a Turnstile: Pause thread from another thread(s) and also stop/start it yet from another thread
Or do you need "one-shot" behavior? (i.e., the "background" thread does one thing each time the "foreground" thread gives it permission to go.) That would be a good application for a java.util.concurrent.Semaphore.
Or, do you need some other behavior?
using an ExecutorService and calling invokeAll might also be an option.
http://docs.oracle.com/javase/7/docs/api/java/util/concurrent/ExecutorService.html
this way lets you also specify a timeout in which all tasks should have been finished. Which is generally a very good idea, if you want to have a responsive application.
Inspired by other answers, I found two solutions:
First:
Create Semaphore with no (0) permits:Semaphore semaphore = new Semaphore(0); in first thread. And share reference to it with your second thread.
Do some work in the first thread and call semaphore.acquire(); when you wish to stop execution.
Some time later call semaphore.release(); from second thread to unblock the first one.
Second:
Create CountDownLatch with initial count 1: CountDownLatch countDownLatch = new CountDownLatch (1); And again, share reference to it with both threads.
Call countDownLatch.await(); when you wish to block execution of the first thread.
The first thread can be resumed by calling countDownLatch.countDown(); somewhere in the second thread.
I am runnning ExecutorService to perform a heavy computation, however I don't want to pollute the algorithmic class/method code with runner operations, in this case I'd like to do periodical check if it should be terminated gracefully.
I tried to search for solutions, still with no success, what I concluded is that this is not possible because only the thread itself is allowed to "autokill himself".
So my question is, if there is any way to terminate the thread "outside" of the thread by invoking some forcefull atempt to kill the thread.
If not maybe the best solution is to use aspect and intercept each iteration by adding a kill status check ?
You can call thread.interrupt(). This can cause thread to exit if it "respects" interruptions. For example if thread is blocked on IO or on wait() or on sleep() InterruptedExcption will be thrown. However if it is "blocked" on busy loop that does not check isInterrupted() flag interruption will not work.
Other way to indeed kill the thread is to call deprecated method stop(). However this is the last possibility. This method is deprecated because it indeed kills threads immediately (like kill -9) that can cause resource leaks.
Bottom line: to be able to stop threads grecefully you have to write code that is ready for this and the standard solution is to respect thread interrupts.
There sure is a way to forcefully terminate a thread: Thread#stop, but it is almost never advisable. Your idea with aspects seems quite fruitful, but if you have any sort of a main loop in your task, then consider replacing the loop with a series of submitted tasks where each task is one iteration. This will allow ExecutorService#shutdown to interrupt the processing. All state can be carried along in the instance of Runnable that is being submitted.
I haven't used the ExecutorService much. But reading the JavaDocs it appears that you submit a callable or runnable to the service. Those methods return a Future object which have a cancel method on it.
cancel(boolean mayInterruptIfRunning)
Have you tried using that?
The method thread.interrupt() stop the thread and you can call it outside the thread itself!
If you do not want to change the original implementation, you could wrap the thread. I'm not very familar with Java, so I'm sorry for the obviously not compiling example:
class ThreadWrapper extends Thread {
public ThreadWrapper(Thread t, TerminateCallback c) {
// ...
}
#Override
public void run() {
t.start(Thread.SYNCHRONOUS);
c.done(this);
}
}
You'd need to implement TerminateCallback yourself. I also assume there is a way to start a thread synchronously, Thread.SYNCHRONOUS is just a place holder. If this condition is fulfilled, I'm sure you can transfer it into valid code. :)
I am trying to stop a current thread, change the run() method, and then restart that thread. I've looked around, and most of the methods are deprecated. However, interrupt() is not. I'm not sure if that's all you need to do.
interrupt();
start();
Would that work for what I needed it to do? It says that you should never start a thread more than once, and I don't know if it means
start();
start();
Rather than what I wanted to do.
Any help is appreciated.
Thanks
No, you can't do that. Fron the java online docs:
It is never legal to start a thread more than once. In particular, a thread may not be restarted once it has completed execution.
Don't restart a thread. You ALWAYS can rewrite your buisness logic to do this some other way. Consider using SingleThreadExecutor
In this case, you should create a Runnable object and pass it to a thread. Then you're creating different threads, but re-using the 'work' object.
Once you've started a thread, you can only interrupt it. Once you've done that, you can't start it again. See here for more details.
I'm not quite sure what you want to do, but it sounds like you have different Runnables that you want to run in sequence. In this case use a SingleThreadExecutor and submit your Runnables. It will run these in order, and so interrupting the first (successfully) will invoke the second.
I'm still not sure this is a good idea (it just doesn't sound right) and perhaps posting a more detailed problem description will give people a better idea of what you're really trying to do.
You should look into the basics of threading more. A thread can only run once. If you want to have the thread run different code, you need to create a new thread.
The interrupt() method will not stop a thread immediately (there is no supported) way to do that, it will stop only at certain points by throwing an InterruptedException().
I think you're approaching your problem in the wrong way. You cannot 'change the run() method of a Thread'. However what you probably want is to stop the previous thread and create a new one with a different run() method.
One thing to keep in mind however, is that Threads are designed to be as autonomous as possible and they don't like interference from other threads, which is why suspend() and resume() are deprecated. They create all sorts of bad behaviour depending on the circumstances and also prone to deadlocks.
You have 2 perfectly safe alternatives however:
Use wait() and notify() on a specific shared object.
Use sleep() and interrupt()
You need to decide within the run() method where it is safe to 'stop' the thread, and at that point put a wait() or sleep(). Your thread will only stop at that point.
The other thread can then do a notify() or sleep() so that the running thread is notified or interrupted. In case of interrupt() you will get an InterruptedException which you can use to terminate what you were doing in that thread.
After interrupting the old thread you can start a new thread initialised with a new Runnable implementation which has the different run() method.
Calling interrupt() will set the thread's interrupt status potentially interrupting blocking methods. This is part of a cooperative cancellation mechanism. You can't use it to force the thread to stop running.
Stopping threads has been deprecated for a reason: it is inherently dangerous as it may leave the state variables which it is manipulating in an inconsistent state.
You should not do this. Make your code from the run() method into a Runnable and submit it for execution to an Executor. This will return you a Future which you can use to retrieve its results as well as to cancel it.
If you want to reuse the same thread for other computations, use a thread pool, see for example Executors.newFixedThreadPool() and other factory methods in Executors.
I am a building a console Sudoku Solver where the main objective is raw speed.
I now have a ManagerThread that starts WorkerThreads to compute the neibhbors of each cell. So one WorkerThread is started for each cell right now. How can I re-use an existing thread that has completed its work?
The Thread Pool Pattern seems to be the solution, but I don't understand what to do to prevent the thread from dying once its job has been completed.
ps : I do not expect to gain much performance for this particular task, just want to experiment how multi-threading works before applying it to the more complex parts of the code.
Thanks
Have a look at the Java SE provided java.util.concurrent API. You can create a threadpool using Executors#newFixedThreadPool() and you can submit tasks using the ExecutorService methods. No need to reinvent your own threadpool. Also see the Sun tutorial on the subject.
when using a thread pool (java.util.concurrent) , you never actually initialized a thread - but rather pass Runnables to the thread pool.
you don't need to worry about the thread life-cycle, just do whatever work you need to do in the runnable and let it exit when it's done.
Have a look into using CyclicBarrier synchro: http://java.sun.com/j2se/1.5.0/docs/api/java/util/concurrent/CyclicBarrier.html
Well, if I had to code this logic my self instead of using a package like Quartz from OpenSymphony, I would do the following:
I'd have a WorkerThread which extends Thread. This class will also have private property called runnable which is Runnable. This property will hold a reference to the code you'd like to execute. Have a public setter for it.
The main thread code will start by running the runnable you initialized it with and then switch to a wait state. Before doing that, it will mark to the pool manager that it has finished and it can be returned to the pool. Next time you need a thread, you pick one from the pool, call setRunnable which sets the property runnable, and then wakes up the thread. It will spawn back to work, enter the infinite loop: execute and runnable and go back to wait state.
What I need is a method similar to shutdownNow, but, be able to submit new tasks after that. My ThreadPoolExecutor will be accepting a random number of tasks during my program execution.
You can grab the Future of each submission, store that Future in a collection, then when you want to cancel the tasks, invoke future.cancel() of all queued tasks.
With this solution the Exectuor is still running and any running tasks are cancelled or will not run if they are queued.
Why not create your own ExecutorService that exhibits this behaviour?
Is it not enough to just do getQueue() and clear it? If you really need to attempt to stop running tasks, you would need to subclass the ThreadPoolExecutor and essentially re-implement shutdownNow() but only copy the bit that sends an interrupt to each thread. Mind you this still isn't any guarantee that you will actually cause them to immediately cease and do no further calculation. You'll need a totally different approach if you need to do that.