So, I have a main thread that spawns a bunch of "worker-threads" that works alongside it for the duration of the process. What I want is that if a worker-thread dies from an exception or whatnot, the main thread should also throw a runtime-exception and die peacefully.
This can be achieved by catching the exception in the worker-tread and setting an error-flag before exiting. The main thread then polls this flag and throws an exception if it's set. This can be done by try-catch or setting an exception handler.
My question is whether there's a simpler way that doesn't include polling in the main thread. Something that goes automatic if you know what I mean.
Edit:
Well, many claim that setting a handler is the answer and that this is a duplicate. Well, unless I'm mistaking things here, the handler is executed by the thread that throws the exception in the first place, so I still have to set a flag to kill the main thread. I thought this was clear. SO let me clarify;
What I want is that if a worker-thread dies from an exception or whatnot, the main thread should also throw a runtime-exception and die peacefully, without using flags, but have it done "automatically"
Have a CountdownLatch in the main thread, have it wait on the CountdownLatch.
When a thread exits decrement the CountdownLatch. When that happens have the main thread act appropriately.
Related
In Akka documentation, there was a part talked about "The illusion of a call stack", um attaching a picture for a part of it. I don't get what he is talking about, I mean if the main thread in java created a new thread and start it if any exception thrown in the created thread the main thread will be notified, so why he is saying that the "caller" will not be notified?!
I mean if the main thread in java created a new thread and start it if any exception thrown in the created thread the main thread will be notified
That is false. Unless the main thread explicitly sets up an uncaught exception handler, it will not be notified of any exceptions in thread it launches (and the uncaught exception handler will also not run in the main thread, so technically the main thread isn't notified at all).
The "illusion of a call stack" is about the fact that the conceptual flow of logic no longer fits the physical call stack when you use things like work queues to schedule separate tasks on other threads.
The actual call stack of any failing sub-task on such a queue will show code related to handling the queue but will not show the calls stack related to the code that initially queued the task which is arguably the more interesting one in many cases.
Problem:
I wanted to know when a RunTimeException is thrown in run method of thread, will thread local of that thread be preserved? Answer to this question lies in what I'm asking below. So with that said, if thread dies(when exception is thrown) it's thread local snapshot get's cleared up or if thread does not die what happens to thread local in that case. Do we need to programmatically handle that?
Scenario:
During heavy load, request came in and processing took way too long and before response was created, async context times out. What happens in this scenario? What happens to the thread that is processing the request?
Here's more details :
I've been researching on how ThreadPoolExecutors internally work. What I'm curious to know is what happens when a RunTimeException is thrown in run method of thread. Does it get killed and ThreadPoolExecutor ends up creating brand new thread? Or JVM somehow does not let that thread to die, so that it can reused in
the pool. I think the thread dies and so does it's ThreadLocal snapshot.
I wanted to get some insight on exactly how ThreadPoolExecutor handle exceptions and how life cycle of a particular thread revolves around that.
Thanks for your help!
Thanks everyone! I got my answer.
Thread dies when an exception is thrown. Only catch here is if we reference a thread id in thread local that can cause a thread leak if that is not cleared properly.
Thread id can be reused as per java docs. In my case I was putting putting some stuff in thread local referencing to thread id (Thread.currentThread.getId). Best way to clear that up is to override afterExecute(java.lang.Runnable, java.lang.Throwable) and clean up things in there.
From java docs:
public long getId()
Returns the identifier of this Thread. The thread ID is a positive long number generated when this thread was created. The thread ID is unique and remains unchanged during its lifetime. When a thread is terminated, this thread ID may be reused.
I am holding a list of Threads, each associated with a Runnable. After running them for a while, some of them changed into the state TERMINATED, though they shouldn't because of while(true) implemented in run(). So I guess those are crashed, am I right?
edit: each thread is independent from the others.
They may have thrown an exception themselves, or been interrupted by another thread. I assume that there's no flow control you've implemented to jump out of the while loop (via an exception) and then cleanly complete processing.
I have a class XYZ which extends Thread and it is also a singleton (Yes. My application needs that).
In the run method, I have something like this:
public void run() {
service.start();
}
The time it takes for service.start() is huge.
Also, my application will not always need the thread to be run but can't decide in advance so while launching the application I am starting this thread.
Now, when application doesn't need the thread, it gets completed very quickly and all I need to do is wait for thread to die.
I tried to use stop() method but came to know that it is deprecated.
See this article for alternatives to calling stop()
http://docs.oracle.com/javase/1.5.0/docs/guide/misc/threadPrimitiveDeprecation.html
stop has been deprecated a long time ago and should not be used. Thread termination is a cooperative process in Java (i.e. the interrupted code must do something when asked to stop, not the interrupting code) - one way is to call thread.interrupt() on the thread you need to interrupt.
You then need to catch the generated interrupted exception in the running thread or check the interrupted status regularly. Once the running thread detects that is should stop what it's doing, you can then run any cleanup tasks as required and exit whatever you were doing.
Signal your thread to do it's cleanup stuff, which you said is fast anyway, then just do a Thread.join.
Your question is highly dependant on exactly what is going on in service.start(). If it's opening external resources, then naturally you can't just barge in and kill the thread without proper cleanup. The start procedure will need to be coded explicitly for interruptibility with proper cleanup.
I understand what an InterruptedException does and why it is thrown. However in my application I get it when waiting for SwingUtilities.invokeAndWait() on a thread that is only known by my application, and my application never calls Thread.interrupt() on any thread, also it never passes the reference of the thread on to anyone.
So my question is: Who interrupts my thread?
Is there any way to tell? Is there a reason why the InterruptedException doesn't contain the name of the Thread that requests the interrupt?
I read that it could be a framework or library that does this, we use the following, but I can't think of reason for them to interrupt my thread:
Hibernate
Spring
Log4J
Mysql connector
If possible, you could extend Thread and overwrite the interrupt() method for this thread to print a stacktrace or throw an unsupported operation exception.
You could also use the extended Thread class to store a reference to the interrupting thread and read it once you catch the interrupted exception.
In general, if you want to know who is doing something, attach a debugger, put a breakpoint, and there you go. No need for guessing if you can reproduce it!
In this case, you can put a breakpoint at Thread.interrupt(). If there are other threads that are being interrupted too (so you have "false positive" hits on the breakpoint), you could add a breakpoint condition (most IDE's allow you to do that easily), for example by checking the name of the thread.
There is something strange here.
From the javadoc of invokeAndWait, an InterruptedException is thrown
if we're interrupted while waiting for the event dispatching thread to finish excecuting doRun.run()
Have you tried to see if the code executed in the EDT sends any exception ? Or do the code in that EDT tries to modify some of this thread's variables (I know this term is not "orthodox" in java language, but I hope you see what I mean : any code implying synchronized, wait, join, ...