Code which I am trying
public void killJob(String thread_id)throws RemoteException{
Thread t1 = new Thread(a);
t1.suspend();
}
How can we suspend/pause thread based on its id?
Thread.suspend is deprecated,There must be some alternative to achieve this.
I have thread id I want to suspend and kill the thread.
Edit: I used this.
AcQueryExecutor a=new AcQueryExecutor(thread_id_id);
Thread t1 = new Thread(a);
t1.interrupt();
while (t1.isInterrupted()) {
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
t1.interrupt();
return;
}
}
But I am not able to stop this thread.
How can we suspend/pause thread based on its id? ... I have thread id I want to suspend and kill the thread.
The right way to kill a thread these days is to interrupt() it. That sets the Thread.isInterrupted() to true and causes wait(), sleep(), and a couple other methods to throw InterruptedException.
Inside of your thread code, you should be doing something like the following which checks to make sure that it has not been interrupted.
// run our thread while we have not been interrupted
while (!Thread.currentThread().isInterrupted()) {
// do your thread processing code ...
}
Here's an example of how to handle interrupted exception inside of a thread:
try {
Thread.sleep(...);
} catch (InterruptedException e) {
// always good practice because throwing the exception clears the flag
Thread.currentThread().interrupt();
// most likely we should stop the thread if we are interrupted
return;
}
The right way to suspend a thread is a bit harder. You could set some sort of volatile boolean suspended flag for the thread that it would pay attention to. You could also use object.wait() to suspend a thread and then object.notify() to start it running again.
I posted a PauseableThread implementation recently that uses a ReadWriteLock internally. Use one of these or a variant and you should be able to pause your threads.
As to pausing them by id, a little googling suggests a way to iterate over all threads which looks like it should work. Thread has exposed a getId method for some time.
Killing the thread is different. #Gray has neatly covered that one.
Related
I'd like to start/stop a thread when I click a button.
Here is what I tried to do.
Thread thread;
String c = classMain.classes.get(a);
Class c1 = Class.forName(c);
Method ref = c1.getMethod("ref");
Object rex = c1.newInstance();
thread = new Thread(new Runnable() {
public void run() {
try {
running = true;
ref.invoke(rex, null);
} catch (IllegalAccessException | IllegalArgumentException | InvocationTargetException e) {
e.printStackTrace();
}
}
});
if (isRunning() == true) {
System.out.println("Here");
running = false;
thread.interrupt();
thread.join();
} else {
thread.start();
}
For some reason interrupt() and join() don't stop the thread.
What should I do? Am I missing something?
EDIT
Alright, so I found a quick and dirty solution for this: throw a custom exception.
I'll explain better:
Instead of thread.interrupt() and thread.join(), I launch a reflected method called interrupt.
It launches an exception, that makes the Thread collapse, thus instant termination.
I am not sure whether this is efficient or not (I have to say that the method I call is a test made with Selenium, and theoretically, it should not waste resources when closed like this), so if you know more let me know.
You might want to read up on what join and interrupt do.
join just wait's for the thread to finish, interrupt just sends the interrupt signal to the thread, which normally does nothing, it will only work if the thread is waiting for some IO or similar. The interrupt signal is normally used to shut down a thread, but it is entirely up the the thread to check for it and shut down properly if it is received. Your question does not give enough detail about what is going on in your second thread to tell if this should work.
If you for some reason cannot change the code run in the thread to make it listen to interrupt you can use Thread.stop instead. It is however deprecated since using it can be dangerous since it is prone to causing deadlocks. The Javadoc for Thread links to several excellent resources on the subject.
Also note that it is illegal to start a thread more than once, which seems like what you are trying to do. You will instead need to recreate it. (as in calling new Thread and start again.)
I've a few questions around ExecutorService and the shutdown process.
My use case:
I use an ExecutorService to spawn a fixed number of threads whose run method look like this:
while (true) {
try {
this.currentThreadRunning = true;
processMessage();
}
catch (Throwable e) {
// Keeping the thread alive despite exceptions.
}
}
These threads run infinitely, polling for messages.
What am I trying to do?
I am polling an SQS queue for messages and processing them.
Obviously, in my case, the ExecutorService's shutdown method would not work. When shutdownNow() is called, all my threads are shutdown unceremoniously. I hate it!
Is there a way to invoke awaitTermination and verify, in my Runnable instance(in a finally block?), if shutdown has been initiated and trigger the same for the current thread?
UPDATE: I've refactored my code to perform polling and then spawning threads to process them. Thus, the Runnable instance's run method need not be an endless loop. And awaiTermination will lead to a definite closure of the threads. And to be sure, I've triggered shutdownNow after awaitTermination.
I think what you are doing is conceptually wrong.
awaitTermination is meant to wait for all threads to finish naturally and then stop the executor. When submitting a Runnable, it shouldn't have an idea of the context of it's execution, so, coupling your runnable to your executor is not a good idea IMHO.
Maybe you should look into the Future class and move your Runnable implementation there. Then you will be forced to implement a cancel(boolean) method which you might find useful.
What is exactly your use case? Maybe if you explain it, the community can point out a better suited implementation.
For infinitely running Runnables I rely on catching an InterruptedException, which will typically be thrown from my calling shutdownNow() or occasionally from calling Future#cancel(true)
while(!Thread.interrupted()) {
try {
} catch(InterruptedException e) {
break;
} catch(Throwable e) {
// Keeping the thread alive despite exception
}
}
// Thread was interrupted via shutdownNow(), cleanup resources
If I need to distinguish between a resumable interrupt and a shutdown interrupt then I share an AtomicBoolean doShutdown among my Runnables that is initialized to false and set to true if I want an InterruptedException to terminate the thread.
You have to check the interrupt status of the thread you are running in (see tutorial on interrupts here: https://docs.oracle.com/javase/tutorial/essential/concurrency/interrupt.html). Your code should be:
while (!Thread.currentThread().isInterrupted()) {
try {
this.currentThreadRunning = true;
processMessage();
}
catch (Throwable e) {
// Keeping the thread alive despite exceptions.
}
}
Note however that you do have to handle interrupts correctly in code called from your runnable. If there is anything like the following:
try {
// do something
} catch(InterruptedException e) {
// ignore
}
then this won't work. The correct way to handle InterruptedException is to call Thread.currentThread().interrupt();.
You should not call shutdownNow() But you should only call shutdown and use awaitTermination to wait for some time.
So shutdown would be something like this
Declare a volatile variable
private volatile stopThread = false;
On shutdown you call
this.stopThread = true;
executor.shutdown();
executor.awaitTermination(..
executor.shutdownNow() // in case termination takes too long
And in the thread you check for the stopThread variable. You cannot use isInterrupted here because we are not interrupting the thread. we are just waiting for the thread to exit based on this condition
if(stopThread){
// calling off all the operations and returning
}
I have written an article about shuting down the executorservice properly
http://programtalk.com/java/executorservice-not-shutting-down/
I hope this will help you.
I am creating an program and working with threads in details for the first time and stuck into an situation .Please help me in that.
I am having a thread which is in wait state.Now at some instance I want to kill or to awake thread and resume from another class .For this I am saving object of thread .I don't know how to do this .I tried to notify thread but got exception.Here is my code:
Class one:
Thread t= new Thread(new Runnable() {
#Override
public void run() {
try{
Thread.sleep(VariableClass.THREAD_WAIT_SECONDS);
if(message !=null)
message_status = message.getStatus();
}
catch(InterruptedException e)
{
e.printStackTrace();
}
//do other stuff and save the thread object
VariableClass.threads.remove(message.getUniqueId());
}
});
t.start();
VariableClass.threads.put(pojo.getUniqueId(),t);
Class two:
Thread t =VariableClass.threads.get(tempId);
t.notify();
I just want to resume or kill thread.
If your thread t is sleeping, calling t.interrupt() will cause an InterruptedException to be thrown from the line calling Thread#sleep. It will get caught in your catch block and your thread will proceed from there to do its cleanup and exit.
If there was an issue where your thread was not sleeping or waiting but still wanted to be aware of whether it was interrupted, the code in your Runnable could check the interrupted flag on the current thread. Remember that the interrupted flag gets reset once an InterruptedException is thrown.
Wait and notify are for threads that are synchronizing on a monitor, that's not applicable to your example. Threads wait on a monitor and receive notifications, but the notifications are not made to a specific thread; for Object#notify, some thread waiting on that monitor gets chosen but the thread calling notify has no control over which one is picked.
Here's an example of using interrupt to wake a thread from sleeping.
Your thread is sleeping for the specified amount of time. Call interrupt on it, if you just want to "kill it" and you don't care too much what will happen with it later. You cannot simply "awake it" from another thread, if it's sleeping it has to sleep as much as it has been told to. Calling notify has nothing to do with this situation (there's no prior wait call). Even if did, you're calling it incorrectly.
You do not use notify in this case. I suggest reading the JavaDoc on #wait/#notify/#notifyAll
You use #notify and #notifyAll to create a framework with concurrency such as a Thread that does work on an instance of a certain object and other threads are waiting to work on it.
A thread "dies" out if the run function is over, but if you want to stop the thread immediately, use #interrupt.
In my application each request has its own thread. I use JMX/JConsole to monitor them, measure the elapsed time. If a a request needs too much time I'd like to stop it by interrupting the underlying thread.
In a method that I call from JConsole I iterate over the list of threads and call interrupt() on the right instance.
However simply calling the interrupt() method on the thread instance only sets a flag, so I need to throw an InterruptedException, too.
But this InterruptedException will apply to currentThread instead of the thread I actually want to stop. Any hint how to shut down the flagged thread?
while (iterator.hasNext()) {
RequestHolder rh = iterator.next();
if (rh.getThread().getId() == threadId) {
rh.getThread().interrupt();
if(rh.getThread().isInterrupted()){
throw new InterruptedException();
}
}
}
But this InterruptedException will apply to currentThread instead of the thread I actually want to stop.
You can check the interruption status of any thread using isInterrupted. However, it is not recommended as a black-boxed approach if you don't know how and when the interruption gets consumed.
Any hint how to shut down the flagged thread?
You cannot cleanly shutdown a thread from another thread.
But it is very simple. In the threads that are running, check for Interruption regularly, such as in loop catch InterruptedException for blocking functions. When you see the interruption in the thread, make it terminate itself. In a sense, the Threads implement their own termination policy.
There is no benefit to throwing InterruptedException. Your if (rh.getThread().isInterrupted()) block can be removed.
Each thread must monitor its own interrupted state, and must exit gracefully when it sees that it has been interrupted.
Usually the code looks something like this:
try {
InputStream in = socket.getInputStream();
while (in.read(buffer) >= 0) {
if (Thread.interrupted()) {
logger.log(Level.FINE, "Interrupted; exiting");
break;
}
// Process request buffer here
}
} catch (InterruptedIOException e) {
logger.log(Level.FINE, "Interrupted; exiting", e);
}
If you are using Channels, you'll want to catch ClosedByInterruptException as well.
you can pass the reference of the thread to be terminated in the constructor of the thread responsible for performing the termination of the first one. Then you can destroy the thread using its reference from another thread.
In the below code, i have a while(true) loop.
considering a situation where there is some code in the try block where the thread is supposed to perform some tasks which takes about a minute, but due to some expected problem, it is running for ever. can we stop that thread ?
public class thread1 implements Runnable {
/**
* #param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
thread1 t1 = new thread1();
t1.run();
}
#Override
public void run() {
// TODO Auto-generated method stub
while(true){
try{
Thread.sleep(10);
}
catch(Exception e){
e.printStackTrace();
}
}
}
}
First of all, you are not starting any thread here! You should create a new thread and pass your confusingly named thread1 Runnable to it:
thread1 t1 = new thread1();
final Thread thread = new Thread(t1);
thread.start();
Now, when you really have a thread, there is a built in feature to interrupt running threads, called... interrupt():
thread.interrupt();
However, setting this flag alone does nothing, you have to handle this in your running thread:
while(!Thread.currentThread().isInterrupted()){
try{
Thread.sleep(10);
}
catch(InterruptedException e){
Thread.currentThread().interrupt();
break; //optional, since the while loop conditional should detect the interrupted state
}
catch(Exception e){
e.printStackTrace();
}
Two things to note: while loop will now end when thread isInterrupted(). But if the thread is interrupted during sleep, JVM is so kind it will inform you about by throwing InterruptedException out of sleep(). Catch it and break your loop. That's it!
As for other suggestions:
About Thread.stop():
Deprecated. This method is inherently unsafe[...]
Adding your own flag and keeping an eye on it is fine (just remember to use AtomicBoolean or volatile!), but why bother if JDK already provides you a built-in flag like this? The added benefit is interrupting sleeps, making thread interruption more responsive.
The proper way to stop a thread is to interrupt it (stop() is deprecated and may have nasty side effects):
t1.interrupt()
This will cause an InterruptedException to be thrown by methods like Thread.sleep() or Object.wait().
Then just add a catch block for this exception and simply break out of the while loop.
EDIT: I now realised that your infinite loop is running within the main thread, there's no thread created by your code, it's just run()ning a Runnable. You need to call Thread.start() at some point to spawn a new thread.
Move the catch interrupt to outside the loop. This doesn't require any more lines of code, it just handles interrupts correctly i.e. the action is interrupted.
public void run() {
try{
while(true) {
Thread.sleep(10);
}
} catch(InterruptedException e){
System.out.println("Thread interrupted"));
}
}
The only way to stop an arbitrary thread is by interrupting it. Keep a reference to it then call the interrupt method.
Create a field boolean keepGoing that you set to true before starting your thread and replace while (true) with while (keepGoing). At some point, you decide where, simply change the value of keepGoing to false and it will exit the loop.
I recommend using Thread.interrupt() (as mentioned by #Bohemian). It has a couple of advantages over using ad-hoc flags:
You don't need to create and use an application-specific API to do this. (And interrupts are guaranteed thread-safe ...)
Thread.interrupt() will interrupt threads that are blocked in a wait() or a join, or possibly1 some blocking I/O calls.
However, it is not a magic bullet. If the thread you are trying to stop is executing regular code, it needs to periodically check its interrupted() flag, or it won't no to stop. This leaves us in the same as boat as we are in with an ad-hoc flag mechanism. The thread has to cooperate, or it can't be (safely) stopped.
1 - This is a murky area. On the one hand, there is an InterruptedIOException whose javadoc says "Signals that an I/O operation has been interrupted". On the other hand, the exception is not explicitly mentioned in the javadocs for the various java.io stream classes.
It is true that some 3rd-party code may not deal with the interrupted flag properly, and interrupts may get "eaten" as a result. But you can check for that if you have source code. And the situation is not a lot different to the 3rd-party code not paying attention to your ad-hoc flag mechanism.
I would NOT recommend using Thread.stop(). It is fundamentally flakey. Some people claim that it works for them, but IMO they are either dealing with a special case that works ... or they are being lucky.