multithreaded settings in thread pool timeout exit monitor

Source: Internet
Author: User
Preface

When you write multithreaded procedures, most of the time you first create a thread pool and then create threads, but for some read databases or other IO operations, it is easy to excutor the thread, and then you need to set a time-out for the thread, kill the timeout thread, and then pull up one more thread, But the Java thread created and did not reserve timeout parameters, research on the internet also did not find a good solution, and simply find a way to get a. Programme

Monitoring threads often have such a number of scenarios first thought should be the future get method, there is timeout to set the parameters, but this got method is blocked, for the kind of waiting for the thread to run the results of the need to use it is more convenient, but the use of thread monitoring is all sorts of uncomfortable, In particular, to monitor multiple threads, such as the following article, create several threads and then create the same number of monitoring threads http://blog.csdn.net/dj2442945707/article/details/56292413 another is more common , the IF tag bit in the task, the set tag bit in the other task exits the task, which is a method of thread exit, but cannot be timed out automatically exit the other is to use the interrupt, which means that the thread throws interruptexception to terminate the thread. The Cancel method in future, for example, is to send a signal to a thread by means of a break, but this method can consume an IO thread to exit and not allow the CPU-consuming thread to exit the demand

Project needs, need to complete the following requirements 1. Thread pool Create multithreading 2. A timeout detection for created Threads 3. A thread that has timed out is out of execution, freeing threads in the thread pool

4. When a line blocks until those out, you need to pull up a thread to ensure that the task continues to execute

The completion of the above requirements is actually a thread timeout, thread exit, thread creation combined with the implementation of

The code is as follows:

Package com.alibaba.dbtech.paas.app.adha.test;
Import java.util.ArrayList;
Import Java.util.HashMap;
Import java.util.List;
Import Java.util.Map;
Import Java.util.concurrent.ConcurrentHashMap;
Import Java.util.concurrent.ConcurrentMap;
Import Java.util.concurrent.ExecutorService;
Import java.util.concurrent.Executors;
Import Java.util.concurrent.Future;
Import Java.util.concurrent.ScheduledExecutorService;

Import Java.util.concurrent.TimeUnit;

Import Org.junit.Test; public class Threadmonitortimeouttest {private Concurrentmap<integer, long> alivethreadrefreshtimemap = new Conc
  Urrenthashmap<> ();
  Final Map<integer, future<?>> alivethreadfuturemap = new hashmap<> ();
  private int alivethreadnum = 0;

  Private Executorservice Cachedthreadpool;  private void dootherthing (int mseconds) throws interruptedexception {for (int i = 0; i < 1000; i++) {int J
    = i;

  } thread.sleep (Mseconds); } private Runnable Workerthread (int i, INT Sleeptime) {return new Runnable () {@Override public void run () {try {long)
          Time = System.currenttimemillis ();
          Alivethreadrefreshtimemap.put (i, currenttime);
          System.out.printf ("Worker thread#%s start...\n", i);
            while (true) {dootherthing (sleeptime);
            CurrentTime = System.currenttimemillis ();
          Alivethreadrefreshtimemap.replace (i, currenttime); (Interruptedexception e) {System.out.printf ("thread%d into interruptedexception, over\n", i)

        ;
        catch (Exception e) {//Todo:handle Exception e.printstacktrace ();
  }
      }
    }; Runnable monitorworker = new Runnable () {@Override public void run () {try {System.out.printf
        ("Monitor thread start ..., alivethreadrefreshtimemap:%s\n", Alivethreadrefreshtimemap);
     list<integer> removeidlist = new arraylist<> ();   for (int threadId:aliveThreadRefreshTimeMap.keySet ()) {Long currenttime = System.currenttimemillis ();
          Long refreshtimes = Currenttime-alivethreadrefreshtimemap.get (threadId);
          System.out.printf ("Thread%d, Refreshtimes is%d\n", ThreadId, Refreshtimes); if (Refreshtimes > 10000) {System.out.printf ("Alive thread%d:is%dms to refresh, would restart\n", thread
            Id, Currenttime-alivethreadrefreshtimemap.get (threadId));
            Alivethreadfuturemap.get (ThreadId). Cancel (true);
            Alivethreadnum + +;
            future<?> Future = Cachedthreadpool.submit (Workerthread (Alivethreadnum, alivethreadnum*4000));
            Alivethreadfuturemap.put (alivethreadnum,future);
            Removeidlist.add (THREADID);
          System.out.printf ("Restart success, thread ID is:%d\n", alivethreadnum);
          } for (int id:removeidlist) {alivethreadfuturemap.remove (ID); AlivethreadreFreshtimemap.remove (ID);
      } catch (Exception e) {//Todo:handle Exception e.printstacktrace ();

  }

    }
  };
    @Test public void CreateTask () {cachedthreadpool = Executors.newcachedthreadpool ();
      for (int i = 0; i < 3; i++) {//Alivecachedthreadpool.execute (Adhaalivedetecttask);
      future<?> Future = Cachedthreadpool.submit (Workerthread (i, i*6000));
      Alivethreadfuturemap.put (i, future);
    alivethreadnum++;
    }//Detect monitor task Scheduledexecutorservice Monitorexecutor = Executors.newscheduledthreadpool (1);
    Monitorexecutor.scheduleatfixedrate (monitorworker, 0, 1, timeunit.seconds);
  while (true);
 }
}

Explain:
First, CreateTask
CreateTask (): Create a thread pool and start 3 threads to perform Workerthread
future<?> Future = Cachedthreadpool.submit (Workerthread (i, i*6000)); The purpose of using Future is to call the Cancel method to terminate the thread directly in post monitoring. The reason is i*6000 is to verify the different running state of the thread and the timeout thread that is not timed out
Monitorexecutor Create a timed dispatch thread to perform the monitoring, note that a single thread is used to monitor all threads created in the Excutor thread pool
Second, Workerthread thread
There's no way to explain the endless cycle of running some time-consuming operations.
Third, monitorworker monitoring thread
Monitoring threads is the focus of this program
The whole logic is:

In the C program, the watchdog dog feeds the dog's mind, a unique identifier for each thread, I, maintains a global variable in each thread, which is the current timestamp, each loop updates the latest timestamp, and the monitor thread reads the timestamp (non-blocking) to determine whether the thread timed out. If the timeout call Future.cancel to cancel the thread running, but how many threads in the thread pool future to the timeout thread, it is still the only thread ID (i) that is defined by itself, and how to exit the timeout thread. The interrupt exception that is used here, receives the interrupt signal throws an exception and jumps out of the loop

Four, global variables

Alivethreadrefreshtimemap: Maintains mappings for each thread ID and timestamp to monitor which line blocks until those
Alivethreadfuturemap: maintains mappings for each thread ID and thread return value future, Use to cancel a timeout thread to run using
Alivethreadnum: Records the ID position of the last thread created, used to pull up new threads with a duplicate ID number, to distinguish whether the current thread was reset by timeout or when it was created at startup. Don't dwell on the problem without the Line 3 route, as long as you don't repeat it.
Cachedthreadpool: Still in the cachepool thread pool to pull up a new thread, the reason for using Newcachedthreadpool is to watch his repeated use of threads, When an exiting thread is idle, it allows new threads to reuse print results

Worker thread#0 start ... worker thread#2 start ..., worker thread#1 start ..., alivethreadrefreshtime. map:{0=1511944045190, 1=1511944045188, 2=1511944045188} thread 0, Refreshtimes is 1 thread 1, Refreshtimes is 3 thread 2, Refreshtimes is 3 monitor thread start ..., alivethreadrefreshtimemap:{0=1511944046190, 1=1511944045188, 2 = 1511944045188} thread 0, refreshtimes is 0 thread 1, refreshtimes are 1002 thread 2, refreshtimes is 1003 monitor thread St
Art ..., alivethreadrefreshtimemap:{0=1511944047189, 1=1511944045188, 2=1511944045188} thread 0, Refreshtimes is 1 Thread 1, Refreshtimes is 2002 thread 2, Refreshtimes is 2002 monitor thread start ..., alivethreadrefreshtimemap:{0=151194 4048191, 1=1511944045188, 2=1511944045188} thread 0, refreshtimes is 0 thread 1, refreshtimes is 3004 thread 2, Refreshtim
ES is 3004 monitor thread start ..., alivethreadrefreshtimemap:{0=1511944049193, 1=1511944045188, 2=1511944045188} Thread 0, Refreshtimes is 0 thread 1, Refreshtimes is 40Thread 2, refreshtimes is 4005 monitor thread start ..., alivethreadrefreshtimemap:{0=1511944050193, 1=1511944045188, 2 =1511944045188} thread 0, refreshtimes is 0 thread 1, refreshtimes are 5005 thread 2, refreshtimes is 5006 monitor thread s
Tart ..., alivethreadrefreshtimemap:{0=1511944051193, 1=1511944051193, 2=1511944045188} thread 0, RefreshTimes is 0 Thread 1, refreshtimes is 0 thread 2, refreshtimes is 6006 monitor thread start ..., alivethreadrefreshtimemap:{0=151194405 2190, 1=1511944051193, 2=1511944045188} thread 0, refreshtimes is 0 thread 1, refreshtimes is 999 thread 2, Refreshtimes I s 7004 Monitor thread start ..., alivethreadrefreshtimemap:{0=1511944053192, 1=1511944051193, 2=1511944045188} thread 0, Refreshtimes is 0 thread 1, refreshtimes are 1999 thread 2, refreshtimes is 8005 monitor thread start ..., alivethreadrefres htimemap:{0=1511944054193, 1=1511944051193, 2=1511944045188} thread 0, refreshtimes is 0 thread 1, refreshtimes is 3000th Read 2, Refreshtimes is 9005 monitOr thread start ..., alivethreadrefreshtimemap:{0=1511944055192, 1=1511944051193, 2=1511944045188} thread 0, Refreshtimes is 0 thread 1, refreshtimes is 3999 thread 2, refreshtimes are 10004 alive thread 2:is 10004ms to refresh, WI ll restart thread 2 into the interruptedexception, over worker thread#4 start ... restart success, thread ID is:4 monitor Threa
D-Start ..., alivethreadrefreshtimemap:{0=1511944056193, 1=1511944051193, 4=1511944055193} thread 0, Refreshtimes is 0 Thread 1, Refreshtimes is 5000 thread 4, refreshtimes is 1001 monitor thread start ..., alivethreadrefreshtimemap:{0=151194 4057191, 1=1511944051193, 4=1511944055193} thread 0, refreshtimes is 0 thread 1, refreshtimes is 5998 thread 4, Refreshtim
ES is 1998 monitor thread start ..., alivethreadrefreshtimemap:{0=1511944058193, 1=1511944057193, 4=1511944055193} Thread 0, Refreshtimes is 0 thread 1, refreshtimes are 1000 thread 4, Refreshtimes is 3000 monitor thread start ..., aliveth readrefreshtimemap:{0=1511944059193, 1=151194405714=1511944055193} thread 0, refreshtimes is 0 thread 1, refreshtimes is \ n Thread 4, refreshtimes is 4000 monitor thr
EAD start ..., alivethreadrefreshtimemap:{0=1511944060192, 1=1511944057193, 4=1511944055193} thread 0, Refreshtimes is 0 Thread 1, Refreshtimes is 2999 thread 4, refreshtimes is 4999 monitor thread start ..., alivethreadrefreshtimemap:{0=151194 4061194, 1=1511944057193, 4=1511944055193} thread 0, refreshtimes is 0 thread 1, refreshtimes is 4002 thread 4, Refreshtim
ES is 6002 monitor thread start ..., alivethreadrefreshtimemap:{0=1511944062191, 1=1511944057193, 4=1511944055193} Thread 0, Refreshtimes is 0 thread 1, refreshtimes are 4998 thread 4, refreshtimes is 6998 monitor thread start ..., aliveth readrefreshtimemap:{0=1511944063191, 1=1511944057193, 4=1511944055193} thread 0, refreshtimes is 0 thread 1, Refreshtimes is 5999 thread 4, refreshtimes is 7999 monitor thread start ..., alivethreadrefreshtimemap:{0=1511944064192, 1 =1511944063196, 4=1511944055193} thread 0, REFREshtimes is 0 thread 1, refreshtimes are 996 thread 4, refreshtimes is 8999 monitor thread start ..., alivethreadrefreshtime map:{0=1511944065193, 1=1511944063196, 4=1511944055193} thread 0, refreshtimes is 0 thread 1, refreshtimes is 1998 thread 4, Refreshtimes is 10001 alive thread 4:is 10001ms to refresh, would restart restart, thread ID success worker thread #5 start ... thread 4 into interruptedexception, over monitor thread start ..., alivethreadrefreshtimemap:{0=1511944066193 , 1=1511944063196, 5=1511944065194} thread 0, Refreshtimes is 1 thread 1, refreshtimes are 2998 thread 5, Refreshtimes is 1 000

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.