In layman's Java Concurrency (36): Thread pool Part 9 concurrency Operation exception System [GO]

Source: Internet
Author: User

and the tool class introduced by the contract many methods throw a certain exception that describes the exceptions that occur when the task is executed in the thread pool, and usually these exceptions require the application to capture and process.

For example, the following API is available in the future interface:

Java.util.concurrent.Future.get (Long, timeunit) throws Interruptedexception, Executionexception, timeoutexception;

The specific implementation principles of the future class are described in the previous chapters. No longer discussed here, but more curious about the thrown three exceptions.

Here is an article (Java Theory and Practice: dealing with Interruptedexception) that describes the origin and processing of interruptedexception. Simply put, the thread is interrupted by itself or by others during execution. The current exception needs to be handled in response to interrupts.

For Java.lang.Thread, Interruptedexception is also a very strange problem.

Interrupts a thread of threads. interrupt () triggers one of the following:

If the thread is calling the wait (), wait (long), or wait (long, int) method of the Object class, or the class's join (), join (long), join (long, int), sleep (long), or sleep (long , int) is blocked during the method, its interrupt state is cleared, and it will receive a interruptedexception.

Detects the interrupt state of a thread is described as such thread. interrupted ():

Test if the front thread has been interrupted. The interrupt state of the thread is purged by this method. In other words, if the method is called twice in a row, the second call will return False (except in the case where the current thread is interrupted again until the first call has cleared its break state and the second call has finished verifying the break state).

That is, if a thread has been detected to have been interrupted, then the thread's consumer (pending, waiting, or executing) should be given a break exception, and the abnormal interrupt state will be cleared.

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 method implementation that gets the result of the task above, an interrupt exception is obtained during the acquisition of the lock. The code java.util.concurrent.locks.AbstractQueuedSynchronizer.tryAcquireSharedNanos (int, long) describes the situation:

Public final Boolean Tryacquiresharednanos (int arg, long nanostimeout) throws Interruptedexception {
if (thread.interrupted ())
throw new Interruptedexception ();
return tryacquireshared (ARG) >= 0 | |
Doacquiresharednanos (ARG, nanostimeout);
}

This detects the thread break when the lock is acquired and, if interrupted, clears the interrupt bit and throws an interrupt exception. Why do you do this? Because our threads are repeatedly executed in the thread pool, once the thread has been interrupted it does not exit the thread, but instead sets the interrupt bit and waits for the task queue to process the thread itself, thus achieving the purpose of the thread being reused. Interested can refer to code java.util.concurrent.ThreadPoolExecutor.Worker.runTask (Runnable). This causes all threads to be interrupted when the thread pool is closed.

Except Interruptedexception. Exception we also found a brand new exception java.util.concurrent.TimeoutException, which is used to describe the task execution time exceeding the expected wait time, perhaps has not been acquired to the lock, perhaps has not done.

In the Innerget code snippet we see that if a thread fails to acquire a lock at a specified time, a timeout exception is obtained. This is a good understanding, for example, if you perform a very time-consuming network task, we do not want the task to wait for a large amount of resources, and you may want to cancel the operation after a certain amount of time. The time-out exception is a good description of this requirement.

At the same time, if you cancel a task and then get the execution result from the task again, you will get an exception java.util.concurrent.CancellationException the task is canceled.

In addition to the above exception, you will get a java.util.concurrent.ExecutionException exception,

This is because our submitted task java.util.concurrent.Callable allows any exception to be thrown in the call () method, and the regular thread execution may throw a runtimeexception, so it simply wraps up all the exceptions, Executionexception thrown as an exception that occurs during execution.

The above is the entire anomaly system, all concurrent operation exceptions can be attributed to the above categories.

In many cases processing time is Java.util.concurrent.TimeUnit, which is an enumeration type used to describe the length of time. Some units of length are built into them. These include nanoseconds, microseconds, milliseconds, seconds, minutes, hours, and days. For example, a timeout operation of 5 seconds, you can use

Future.get (5,timeunit.seconds) or Future.get (5000l,timeunit.milliseconds)

Of course, the time to convert a unit of time into another unit is also very convenient. In addition, the sleep/join of the thread and the convenient operation of the object's wait operation.

In layman's Java Concurrency (36): Thread pool Part 9 concurrency Operation exception System [GO]

Related Article

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.