Why the unhanded exception is rethrown in worker when calling execute method ? As result new Thread will be created on next execution to maximize threads count
Why java ThreadPoolExecutor kill thread when RuntimeException occurs?
I can only guess that the reason why ThreadPoolExecutor.execute(...) has the thread call runnable.run() directly and not wrap it in a FutureTask is so you would not incur the overhead of the FutureTask if you didn't care about the result.
If your thread throws a RuntimeException, which is hopefully a rare thing, and there is no mechanism to return the exception to the caller then why pay for the wrapping class? So worst case, the thread is killed and will be reaped and restarted by the thread-pool.
There is no way to handle exception properly. Exception can't be propagated to caller thread and can't be simply swallowed.
Unhandled exception is thrown in thread is delegated to ThreadGroup.uncaughtException method, which prints output to System.err.print, until desired behavior is overridden for ThreadGroup.
So this is expected behavior, it can be compared with throwing unhanded exception in main method. In this case, JVM terminates execution and prints exception to the output.
But I'm not sure, why ThreadPoolExecutor does not handle it itself, ThreadPoolExecutor can log it itself. Creating new Thread is not so cheap.
Maybe there is an assumption, that some resources (native, threadLocal, threadStack, etc) associated with Thread should be released.
Related
While going through the javadoc for the notifyAll() method under Object class came through the following lines:
If the current thread is interrupted by any thread before or while it is waiting, then an
InterruptedException is thrown. This exception is not thrown until the lock status of this object has been restored as described above.
The point is:
the current thread is interrupted while it is waiting
What does this means? Can a thread be interrupted while it is waiting?
If yes, why? What is the use of it?
The meaning of "thread getting interrupted" in Java means that the thread's interrupted flag has been set, nothing more. However, most methods of the JDK which make the thread wait will immediately find out about this and exit the wait state, throwing an InterruptedException. Such is the case with the methods you have been reading about.
A thread can be interrupted while waiting if another thread calls:
waitingThread.interrupt();
This can happen if you do it yourself of course but also if you use a framework to manage your threads, typically an executor service, and call some of the methods that interrupt the underlying threads (e.g. shutdownNow or if you call future.cancel(true); on the Future returned by the submit method).
The interruption mechanism is how Java enables one thread to tell another one to stop what it is doing and is therefore extremely useful.
I need to know what happens
when it is sleeping?
when it is running i.e., it is executing the given task.
Thanks in advance.
Interrupting a thread is a state-safe way to cancel it, but the thread itself has to be coded to pay attention to interrupts. Long, blocking Java operations that throw InterruptedException will throw that exception if an .interrupt() occurs while that thread is executing.
The .interrupt() method sets the "interrupted" flag for that thread and interrupts any IO or sleep operations. It does nothing else, so it's up to your program to respond appropriately- and check its interrupt flag, via Thread.interrupted(), at regular intervals.
If a thread doesn't check for interruptions, it cannot safely be stopped. Thread.stop() is unsafe to use. So you use .interrupt() to stop a thread, but when writing multithreaded code, it is up to you to make sure that .interrupt() will do something sensible. This TechRepublic article is a pretty good tutorial.
Judging by your previous questions, I assume you are interested in Java's behavior.
In Java, an InterruptedException will be thrown if the thread is currently blocking. If the thread is not blocking, the exception will not be thrown.
For more information, look here:
JavaDocs
For .NET languages, a ThreadInterruptedException will be thrown if the thread is currently blocking. If the thread isn't blocking the exception will not be thrown until the thread blocks.
Please tag your question with the language you want an answer for.
One more important information worth sharing is that, there are two methods in Thread Class
isInterrupted() and interrupted(). Latter one being a static method. isInterrupted() method call does not alter the state of interrupted attribute of Thread class, whereas interrupted() static method call can will set the value of interrupted boolean value to false.
I am asking because if it is not, it can be abused as synchronizations mechanism. I am asking about Java.
I'm not sure what you mean by "can be abused as synchronizations mechanism" - that doesn't make sense.
Exceptions are per thread - when an exception is thrown, the current thread's execution jumps to the place where the exception is caught. If it's not caught at all, the thread dies. Other threads are not affected.
JLS 11.3.2 Handling Asynchronous Exceptions
Most exceptions occur synchronously as a result of an action by the thread in which they occur, and at a point in the program that is specified to possibly result in such an exception. An asynchronous exception is, by contrast, an exception that can potentially occur at any point in the execution of a program.
Proper understanding of the semantics of asynchronous exceptions is necessary if high-quality machine code is to be generated.
Asynchronous exceptions are rare. They occur only as a result of:
An invocation of the stop methods of class Thread or ThreadGroup
An internal error in the Java virtual machine
So no, while rare, not all Exception handling is synchronous.
No, it's synchronous.
Try stepping through your code with a debugger, you'll see that it executes line after line, and will not continue if you break inside the catch.
Exceptions occur during the execution of a thread. It does not make sense to have an asynchronous catch because the thread has to handle the exception. It cannot proceed till the exception is caught and taken care of. If the exception is not caught or thrown, the thread does not know what it has to do and simple dies and the program may/may not misbehave.
A thread throwing an exception and then proceeding without waiting for the catch does not make sense.
To answer your question, no catching is not asynchronous for all practical purposes.
I have a java.util.concurrent.Execution service - a single threaded thread pool executor. I submit certain tasks to it. If the task throws an unchecked exception the thread dies but the service ensures that a new thread is spawned and subsequent tasks are performed in that. However I do not want this feature and still want to use a threadPoolExecutor. i.e. I want the service to shutDownNow() if the task throws an unchecked exception.
What is the best way to achieve this? Would using a custom thread factory which restricts the number of threads spawned make good sense?
You can create a ThreadPoolExecutor subclass and override the afterExecute method. The method has a throwable parameter that will be non-null if there was an exception.
You could wrap your threadPoolExecutor in an ExecutorCompletionService. Then continually take() from it, retrieving Futures. If future.get() throws an Exception, call threadpoolexecutor.shutdown().
I'm relatively new to Threading in Java and I've noticed that everytime I use Thread.sleep() I have to catch InterrupetdException.
What kind of behaviour causes this, and in simple applications where I have a monitor thread can I just Ignore the exception?
It happens when something calls interrupt() on the thread. This article by Brian Goetz explains the interruption mechanism and how you should handle InterruptedExceptions:
"The most common response to InterruptedException is to swallow it -- catch it and do nothing (or perhaps log it, which isn't any better) -- as we'll see later in Listing 4. Unfortunately, this approach throws away important information about the fact that an interrupt occurred, which could compromise the application's ability to cancel activities or shut down in a timely manner."
"If you catch InterruptedException but cannot rethrow it, you should preserve evidence that the interruption occurred [...]. This task is accomplished by calling interrupt() to "reinterrupt" the current thread."
As others have said, it is caused by some other thread calling interrupt() on the Thread object that is sleeping.
What this means in plain english, is that some other thread has decided to cancel the sleeping thread. The try/catch block is there so you can gracefully handle the cancellation of the thread, and safely clean up any resources, or shut down whatever operation it was doing correctly.
If you don't actually need to do any of that, then yes, you still need an empty catch block. But that's Java for you...
Some advices from Java Concurrency in Practice:
Propagate the exception (possibly after some task-specific cleanup), making your method an interruptible blocking method, too; or
Restore the interruption status so that code higher up on the call stack can deal with it.
Only code that implements a thread's interruption policy may swallow an interruption request. General-purpose task and library code should never swallow interruption requests.
The primary case is when someone calls Thread.interrupt() on your thread.
It may be safer to throw a RuntimeException if it happens when you're really not expecting it, but for very simple cases you can probably ignore it.
From the javadocs:
Class InterruptedException
Thrown when a thread is waiting,
sleeping, or otherwise paused for a
long time and another thread
interrupts it using the interrupt
method in class Thread.
Hope that answers your question.
Well if some other Thread calls thread.interupt(), while the thread is sleeping, you'll get the Exception. And yes, you can probably just put try..catch arround the sleep() and ignore it ;)
InterruptedException is a checked exception so unfortunately you cannot just ignore it. In most simple cases you do not have to do anything in the catch clause because you are sure that it will not happen.
From the API
Thrown when a thread is waiting, sleeping, or otherwise paused for a long time and another thread interrupts it using the interrupt method in class Thread.