Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Best practices for handling InterruptedException [duplicate]

In business scenario, InterruptException occurs multiple times, some before the business code is executed, and some after the business code. How to deal with InterruptException makes me confused.

     1. preBusiness code semaphore.acquire()

        try {
            semaphore.acquire();
        } catch (InterruptedException e) {
           // do something
        }
        resObj = caller.stepTry();
        semaphore.release();
  1. postBusiness code latch.await(), service.take().get()

    CompletionService<CallableResultBO> service = new ExecutorCompletionService<>(executor);
    CountDownLatch latch = new CountDownLatch(size);
    
    for (R callable : listCall){
        callable.setCountParam(JdkThreadCountBO.buildByLatch(latch));
        service.submit(callable);
    }
    
    try {
        latch.await();
    } catch (InterruptedException e) {
        // do something
    }
    
    CallableResultBO[] resArr = new CallableResultBO[size];
    for ( int i = 0; i < size; i++ ){
        try {
            resArr[i] = service.take().get();
        } catch (InterruptedException e) {
            // do something
        } catch (ExecutionException e) {
            // do something
        }
    }
    

    There are also some doubts found in practice, and I am still thinking about how to draw conclusions.      A thread can't be interrupted casually. Even if we set the interrupt state for the thread, it can still get the CPU time slice. Usually only threads blocked by the sleep() method can immediately receive an InterruptedException, so in the case of a sleep interrupt task, you can use try-catch to jump out of the task. In other cases, it is necessary to determine whether the task needs to be jumped out (Thread.interrupted() method) by judging the thread state.

         In addition, the code modified by the synchronized method will not be interrupted immediately after receiving the interrupt signal. The synchronization code of the ReentrantLock lock control can be interrupted by InterruptException.

like image 626
刘海翔 Avatar asked Oct 03 '18 08:10

刘海翔


People also ask

Should you catch InterruptedException?

First of all, you should see throws InterruptedException for what it is: A part of the method signature and a possible outcome of calling the method you're calling. So start by embracing the fact that an InterruptedException is a perfectly valid result of the method call.

Why InterruptedException should not be ignored?

InterruptedExceptions should never be ignored in the code, and simply logging the exception counts in this case as "ignoring". The throwing of the InterruptedException clears the interrupted state of the Thread, so if the exception is not handled properly the information that the thread was interrupted will be lost.

Is InterruptedException a checked exception?

InterruptedException ) is a checked exception [6] which directly extends java. lang. Exception . This exception is thrown when a thread is waiting, sleeping, or otherwise occupied, and the thread is interrupted, either before or during the activity [7].


1 Answers

Generally, you are advised to do the following:

    void methodThatWaits()
    {
        try 
        {
            Thread.sleep( 1000 );
        }
        catch( InterruptedException e )
        {
            //e.printStackTrace();
            Thread.currentThread().interrupt();
        }
    }

So, no, Thread.currentThread().interrupt(); is not redundant.

This is known as the Java Thread.currentThread().interrupt idiom, and it is explained in detail in Java Concurrency in Practice, Chapter 7.1.3. It is also mentioned in Effective Java, you can read an excerpt here: Google Books - Effective Java - search for java idiom thread interrupt interruptedexception josh bloch

like image 97
Mike Nakis Avatar answered Sep 28 '22 21:09

Mike Nakis