Java Concurrency: A thread pool part 9 concurrent operation exception system

Source: Internet
Author: User

Many methods of the tool class introduced by the concurrent sending package throw certain exceptions. These exceptions describe exceptions that occur when the task is executed in the thread pool. These exceptions usually require the application to capture and process them.

For example, the Future interface contains the following API:


Java. util. concurrent. Future. get (long, TimeUnit) throws InterruptedException, ExecutionException, TimeoutException;

The previous section describes the specific implementation principles of the Future class. I will not discuss it here, but I am curious to throw three exceptions.

Here is an article (Java Theory and Practice: InterruptedException) describing the source and processing method of InterruptedException. Simply put, the thread is interrupted by itself or others during execution. In this case, you need to handle the current exception in response to the interruption.

InterruptedException is also a strange problem for java. lang. Thread.

When Thread. interrupt () is interrupted, the following conditions are triggered:

If the thread is calling the wait (), wait (long), or wait (long, int) Methods of the Object class, or the join (), join (long), join (long, when the int), sleep (long), or sleep (long, int) method is blocked, the disconnection state is cleared and an InterruptedException is received.

Thread. interrupted ():

Test whether the current thread has been interrupted. This method clears the thread interruption status. In other words, if this method is called twice in a row, false will be returned for the second call (after the first call has been cleared, and the second call has completed the interruption state, except when the current thread is interrupted again ).

That is to say, if a thread is detected to have been interrupted, the thread user (suspended, waiting, or being executed) will receive an interrupt exception and clear the abnormal interrupt status.

 

V innerGet (long nanosTimeout) throws InterruptedException, ExecutionException, TimeoutException {
If (! TryAcquireSharedNanos (0, nanosTimeout ))
Throw new TimeoutException ();
If (getState () = CANCELLED)
Throw new CancellationException ();
If (exception! = Null)
Throw new ExecutionException (exception );
Return result;
}
 

In the implementation of the method for obtaining the task result above, an exception is thrown when the lock is obtained. The Code java. util. concurrent. locks. AbstractQueuedSynchronizer. tryAcquireSharedNanos (int, long) describes this situation:


Public final boolean tryAcquireSharedNanos (int arg, long nanosTimeout) throws InterruptedException {
If (Thread. interrupted ())
Throw new InterruptedException ();
Return tryAcquireShared (arg)> = 0 |
DoAcquireSharedNanos (arg, nanosTimeout );
}
 

 


The thread interruption is detected when the lock is obtained. If the lock is interrupted, the interrupt bit is cleared and an interrupt exception is thrown. Why? Because our threads are repeatedly executed in the thread pool, once the thread is interrupted, it does not exit the thread, but sets the interrupt bit, waiting for the task queue to process the thread by itself, in this way, threads are reused. For more information, see java. util. concurrent. ThreadPoolExecutor. Worker. runTask (Runnable ). When the thread pool is closed, all threads are interrupted.

In addition to the InterruptedException exception, we also found a completely new exception in java. util. concurrent. timeoutException. This exception is used to describe that the task execution time has exceeded the expected wait time, maybe the lock has not been obtained, or the execution has not been completed.

In the innerGet code snippet, we can see that if the thread cannot get the lock at the specified time, it will get a timeout exception. This is easy to understand. For example, if we want to cancel a network task after a certain period of time without waiting for it to occupy a large amount of resources. This requirement is well described due to timeout exceptions.

At the same time, if a task is canceled, the execution result will be retrieved from the task again, and a java. util. concurrent. CancellationException exception will be returned.

In addition to the preceding exceptions, a java. util. concurrent. ExecutionException exception is returned,

This is because our submitted task java. util. concurrent. callable can throw any exceptions in the call () method, and a RuntimeException may be thrown during regular thread execution. Therefore, all exceptions are simply wrapped up here, it is thrown as an exception ExecutionException during execution.

The above is the entire exception system. All the exceptions of concurrent operations can be attributed to the above types.

In many cases, java. util. concurrent. TimeUnit is used to describe the processing duration. There are some built-in length units. This includes nanoseconds, microseconds, milliseconds, seconds, minutes, hours, and days. For example, if the operation times out for 5 seconds, you can use

Future. get (5, TimeUnit. SECONDS) or Future. get (5000L, TimeUnit. MILLISECONDS)

Of course, converting a unit of time to another unit of time is also very convenient. In addition, there are also convenient operations for sleep/join of threads and wait operations of objects.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.