How can i call the thread itself? - java

Lets say i am in the main method calling a process. Now if this process is stuck or taking too long, normally one can interupt it by interupting the thread.
But incase i have it implemented in the main method not in any external thread, how can i call that current thread itself for interuption like we call say thread.interupt();

Please back up a second. Thread.interrupt only interrupts wait conditions, not computations. There is no Java construct (except the monitoring/debugging agents) for interrupting a computation.
So, if you want a long-running computation to be interruptible, you have to write it to carefully check for interrupts every so often.
If you want to be able to 'interrupt' from outside the process altogether, you will need to handle signals. That's about the only interpretation I've been able to place on your question about the main thread.
This blog post (not mine) has the basic information. From a handler, you could interrupt, for example, the main thread.

You can let another thread interrupt "you" (main). Like this:
final Thread me = Thread.currentThread();
Thread wake_me_up = new Thread(){
#Override
public void run(){
//InterruptionException try catch omitted.
Thread.sleep(200);
me.interrupt();
}
};
wake_me_up.start();
try{
go_into_cave();
}catch(InterruptedException e){
//I got interrupted
System.out.println("thank you, you saved my life");
}
go_home();
While I find it hard to read...

In the main method, you'll have a reference to all Threads. Just get the right reference and do something like this
someThread.interrupt();
Make sure you don't forget to check if the Thread that is running got the flag to interrupt set true.
For example, in the middle of it's method, it needs to be checked if itself isInterrupted() by some Thread else
if(Thread.currentThread().isInterrupted()){
doSomeStuff();
}

You can create a new Thread and call your process from inside the new Thread. Interrupt this thread and catch the exception as per your logic.
I am not sure how to do it only form within the main method, but if your process call is called through a method, just call this method from a new thread and put up a timer in the main method. Once the timer expires, interrupt that thread and you're good to go.

If you're trying to kill the process, because it's hung, why are you even worrying about the thread? Runtime.exec() returns a Process object, which you can use to destroy the subprocess. You should be able to:
Spawn the subprocess, saving the Process object.
Presumably, you're reading the output stream of the process, via what is returned by
Process.getInputStream(). So, continue to do that.
However, spawn a second thread (or use the main thread) to monitor the process. If it
decides that the process has run too long, it can kill it via Process.destroy().
At that point, the first thread should get an EOF or an IOException (stream closed) on
the process's output stream.

Related

problem using isAlive(),Interrupt() and stop() methods of a Thread inside ExecuterService

i have found that isAlive() method is not working when executing a thread using ExecuterService.
And interrupt() and stop() method is also not working.
The code i used:
Thread t1=new Thread(()->{
try{
Thread.sleep(10000);
} catch(InterruptedExeception ie){
System.out.println("Interrupted");
}
Thread.sleep(5000);
System.out.println("It's Done");
});
ExecuterService excuter=Executers.newSingleThreadExecuter();
excuter.execute(t1);
Thread.sleep(2000);
System.out.println(t1.isAlive());
Thread.sleep(2000);
t1.interrupt();
t1.stop();
My expected output is :
true
Interrupted
Actual output is :
false
It's Done
I need reason for this behavior. And I want to know what is the solution for the problem and how I use these methods when a Thread is running inside a ThreadPool.
The stop() method does not work. You can't stop threads like this. A thread needs to opt into allowing itself to be stopped; you'd for example update a (volatile, or AtomicBoolean-style) boolean, and the thread runs a loop, and on each loop, checks that boolean; if it's false, it ends. There is no way to stop arbitrary threads in their tracks. At all. You can google for information about why Thread.stop is deprecated (and effectively doesn't work at all anymore, even though the method is still around, primarily as vehicle for the documentation on why you can't do that anymore).
Threads implement runnable, which is why you're even allowed to pass that thread to the executor method, but the entire thread infra isn't being used at all. You should update this code to be Runnable r = () -> { ... } and pass that. Your code as written is misleading you into thinking that's the thread that is being run. It's not, which is why you're getting false for .isAlive().
Executors as a rule don't expose the way they do the job, they just do it. If you want to check if the job is running, set a (volatile, or AtomicBoolean) boolean to true upon entry, and to false upon exit. Alternatively, don't bother with an executor service, just start your thread, if you really want to use thread functionalities such as .isAlive().
t1 is not a thread.
t1 is a Thread instance, but a Thread instance is not the same thing as a thread, and the way you are using t1, no thread is ever created. Think of a Thread instance as a handle that you use to create and control a thread. The thread would be created if your program called t1.start(), and then the t1.isAlive() and t1.interrupt() and t1.stop() calls all would operate on that new thread.
Besides being a Thread instance, t1 also happens to be a Runnable instance, which is what the executer.execute(...) call wants. Being a Runnable just means that t1 has a run() method. There are various ways that run() method could be called:
You could start the thread, t1.start(), in which case, the new thread would call it,
You could (you did) give it to an Executor. When you do that, the Executor arranges to have one of its worker threads call your run() method.
You could simply call it -- t1.run() -- which is no different from calling any other method that your code defines.
You could pass it to any other library method that wants a Runnable. (I don't know how many there are, maybe a lot.)
If you want t1.run() to be called in a thread that your code can control, then call t1.start() to create that thread. If you want it to be called by an executor service, whose threads you should not attempt to control, then do what you did: call excuter.execute(t1);
Just don't do both. That probably isn't what you want.
P.S., If you want to continue using the Executor service, then you probably should change your declaration of t1. Since it only needs to be a Runnable in that case, you can write:
Thread t1=new Runnable(()->{
...
});
That way, people reading your code won't scratch their heads and wonder whether you knew what you were doing.

Terminate Runnable

I have a task executor which takes runnable as a task. I am starting a timer before calling runnable.run() method and stopping it when the runnable finished. I want to terminate the execution of run() method from the executor itself if the timer exceeds the time limit. I do not know what user will implement in run().
TaskExecutor.add(new Runnable () {
#Override
public void run() {
System.out.println("This is test job");
}}
);
This is how the user adds a new task. Every task runs in the same thread.
Edit
This task executor will act as a service to users. And because creating threads are expensive operation and requires native OS calls, I am trying to avoid them. Otherwise I would call Thread.interrupt() at some point. But I just want to know if there is a way to terminate the run() method from a parent object. Terminate means to stop something abruptly. As how we terminate processes in OS task manager.
How tasks are executed
while (jobQueue.isEmpty()) {
for (Job job : jobQueue) {
long startTime = System.currentTimeMillis();
job.run();
//There is a separate thread which checks
//for timeout flags by comparing the startTime
//with the current time. But all tasks are
//executed in the same thread sequentially. I
//only want to terminate single jobs that are
//timed out.
}
}
you can check condition for your timer,if timer exceeds you can interrupt your thread like-
Thread.currentThread().interrupt();
It will stop your current Thread.
I just want to know if there is a way to terminate the run() method from a parent object.
You can't really terminate a method, and you can't really do anything from an object.
It's often convenient to say "this object does X," or "this method does Y," but objects and methods don't really do anything. When you're talking about multi-threaded code, it's important to realize that everything your program does is done by threads. Methods are just the instructions that tell threads what to do, and objects are what the threads do it to.
You can interrupt a thread, which is only a good idea if the thread is designed to gracefully handle the interrupt; and you can terminate a thread, which basically is never a good idea.
Threads should always cooperate with one another. You need to provide a means by which your program can politely ask the client-provided callback to abort its work and return early. If the client code does not respect your request (i.e., if the client code does not cooperate), that's the client programmer's fault for not obeying your guidelines.
The simplest way to do it would be to simply expose some static boolean method that the client can periodically check to see whether it's time to abort.

Thread interrupt() does not interrupt thread

For some reason, when iterating over a list of threads and interrupting all of them, none of them executes the catch block with InterruptedException.
In the following repository: https://github.com/ranisalt/LiuThread
I have two threads, each of them has executor services and one of them holds readers, the other reads writers. Writers should spawn every 100 ms, write to the buffer and quit/stop/whatever just don't write again. Readers are 4 threads that try to read and, if they can, they should quit too, so there's space for another reader.
I have 100 of each (reader and writer) and if they fail to read or write, they wait 60 seconds.
Then, I have a coordinator thread that keeps testing if the buffer is empty (and interrupts the writers) or full (interrupts the readers), so they never should get to wait 60s. The buffer knows its state.
The problem is, for some reason, this snippet:
for (ThreadAzul azul : threadsAzuis) {
azul.interrupt();
}
Is NOT interrupting the thread! I have used println to see if is getting interrupted:
try {
sleep(60000);
System.out.println(this.getName() + " foi dormir");
} catch (InterruptedException e) {
System.out.println(this.getName() + " foi interrompido");
}
But this NEVER gets written. What is the reason for interrupt() not making the catch block execute?
Inside the main method you are invoking run() on your Thread so you never start a new Thread but instead run its code within the initial main thread. So invoking interrupt on the Thread instance you never have started will not interrupt the main thread which is actually executing the code.
The same error repeats when you submit a Thread instance to an Executor. The executor will execute the run method of the Thread instance because Thread implements Runnable but the Executor will do so within its own managed Thread but not within the Thread represented by the instance you have created but never started.
So again, invoking interrupt on the Thread instance you never have started will not interrupt the thread actually executing the code.
Generally you should not mix Thread and Executor usage. Decide for one way, dealing with Threads manually or using ExecutorSevices.
And when you are using Threads you must start them using the start() method, not invoking the run() method.
Threads only get interrupted during interruptible operations, for example Thread.sleep(), Thread.wait(), and some I/O calls (not all).
Setting the interruptionflag, does not interrupt the Thread. The Thread just ends when it checks, if it is supposed to end. So just give the Thread the chance to check isInterrupted(), or interrupt it while it is sleeping or waiting.
If you have a long-term method in run(), interrupt() will not work. You have to implemet a regularly check or another workaround.

Killing Thread without periodically checking alive status

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. :)

addShutdownHook and setUncaughtExceptionHandler doesn't work as expected in java

I have a multi-threaded program, where I have one thread to watch over several threads. The functioning is designed like this:
Main program does initiation and starts Watcher Thread, in void Main(), I have the line
Runtime.getRuntime().addShutdownHook(new Thread(new ShutdownThread(), "Exit Listener"));
When I don't start the watcher thread, the ShutdownThread is called when I terminate the program, but when I start the Watcher thread which has a dead loop in it, the ShutdownThread is not called (I print out a message in that thread). That is very very strange. Any explanations?
The watcher thread is like:
public void run(){
boolean running=false;
thread a=new thread(...); //Do the same thing for b, c, d...
while(true){
if (a.isActive()){
if (running)
thread a= new thread(...);
a.start();
running=true;
}
Thread.sleep(1000); //try catch block...
}
What I would like is a graceful shutdown, that upon getting a terminate signal, shutdownThread is run, sets a flag and interrupts all threads, and waits for the threads to interrupt it, or it timeout so that the remaining threads can be killed. All the threads can catch an interuption, and check if a flag is set, if set, it will interrupt shutdownThread and then exit itself. Instead what I am seeing is all the threads are terminating by itself, doing no cleanup at all.
How about using signals? Is there any good cross-platform code for that?
Then, setUncaughtExceptionHandler doesn't work either. I did testing, and found that the handler isn't called at all. I don't know why. The code for the handler is:
public static class ErrHandler implements Thread.UncaughtExceptionHandler{
public final void uncaughtException(Thread t, Throwable e) {
Error(t + "died, threw exception: " + e);
}
}//this is in public class globals
I hook it using
producer.setUncaughtExceptionHandler(Globals.errhandler);
Is in my code, and I only see the original e.printStack() instead. It seems that I can't override it, either in the parent thread, or in itself. This is so frustrating. I'm thinking of putting a Entry into a queue, and reading it elsewhere. At least that may work.
Oh, the whole purpose is to make sure that if any of the threads die because of runtime exceptions, the watcher thread will check whether the exception is fatal enough, and decide to restart that thread or to quit altogether. At the same time, I would like the program to end gracefully (an interrupt is sent to saver threads so that it dumps the results out, and then interrupts back to tell that we are ready to quit) when the user ends it.
Dunno if it helps you, but we encountered the same behaviour.
Not all exceptions are routed correctly to the registered ExceptionHandler.
I wonder if Unit-Tests exists at all for the concurrent framework. Because this had to be detected.
We implemented the ScheduledExecutorService by ourself by using a ScheduledExecutorService instance as delegate and encapsulate the parameter Runnable/Callable of each method in a Runnable/Callable implementation which corrects the behaviour.

Categories

Resources