Small knowledge, big challenge! This article is participating in the creation activity of “Essential Tips for Programmers”.

Problem scenario

Threads write Hbase files in batches asynchronously. Normally, millions of data is written to Hbase in batches within 10s. However, there is a problem with online Kerberos authentication, which results in timeout of Hbase PUT retry. As a result, it is difficult for service personnel to quickly sense task execution failure. If a thread executes a temporal process under high concurrency, it can lead to system outages due to thread pool exhaustion, or frequent GC and other exceptions. So how to solve the problem of thread task execution timeout?

The solution

Thread pool + CountDownLatch solves thread execution timeout issues. Create a fixed size thread pool using newFixedThreadPool. This is not recommended by the Ali code specification, but it can be used in appropriate scenarios if we understand the principles of these thread pools. Create a thread pool, execute the task run, hibernate for 60 seconds, create a CountDownLatch counter, and decrease the latch count by one when the thread finishes executing the task. However, we set the wait time of the counter thread to 59 seconds, so when the thread reaches 59 seconds and the task has not finished executing, we close the thread. And then throw an exception.

@Test
public void test(a) {
    ExecutorService executorService = Executors.newFixedThreadPool(1);

    final CountDownLatch countDownLatch = new CountDownLatch(1);

    executorService.execute(new Runnable() {
        @Override
        public void run(a) {
            try {
                Thread.sleep(60 * 1000 );
            } catch (InterruptedException e) {
                e.printStackTrace();
            } finally{ countDownLatch.countDown(); }}});try {
        countDownLatch.await(59, TimeUnit.SECONDS);
        executorService.shutdown();

        if(countDownLatch.getCount()> 0){
            System.out.println("Thread execution timeout..."); }}catch(InterruptedException e) { e.printStackTrace(); }}Copy the code