Java using the default thread pool trampled pits (iii)

Source: Internet
Author: User

                              云智慧(北京)科技有限公司  陈鑫

Restarting the thread pool
TaskManager
public class TaskManager implements Runnable {
.....
Public TaskManager (setrunners) {
Super ();
This.runners = runners;
Executetasks (runners);
}

Private Voidexecutetasks (set<filetask> runners) {for (Filetask task:runners) {pool.execute (Task);    System.out.println (Task.getclass (). Getsimplename () + "has beenstarted"); }} @Overridepublic void Run () {while (!           Thread.CurrentThread (). isinterrupted ()) {try {long current = System.currenttimemillis (); for (Filetask wrapper:runners) {if (Wrapper.getlastexectime ()! = 0 && Current-wrapper.getlastexe                   CTime () > Wrapper.getinterval () * 5 * 1000) {//start forgetting to multiply the wrapper.interrupt (); if (wrapper.getfiles () = null) {for (File file:wrapper.getFiles ()) {fi                       Le.delete ();                   }} System.out.println ("Going to shutdown Thethread pool");    list<runnable> Shutdownnow = Pool.shutdownnow (); Does not wait for the task in the current pool to run out. Directly close the thread pool for (Runnable Run:shutdOwnnow) {System.out.println (run + "goingto be Shutdown"); } while (Pool.awaittermination (1, timeunit.seconds)) {System.out.println ("the THR                       Eadpool has been shutdown "+ new Date ());                   Executetasks (runners);//Run Thread.Sleep again (200);        }}}} catch (Exception E1) {e1.printstacktrace ();        } try {Thread.Sleep (500);  } catch (Interruptedexception e) {}}}public static void Main (string[] args) {set<filetask> tasks =new    Hashset<filetask> ();    Filetask task = Newfiletask ();    Task.setinterval (1);    Task.setname ("task-1");    Tasks.add (Task);    Filetask Task1 = Newfiletask ();   Task1.setinterval (2);    Task.setname ("Task-2");    Tasks.add (TASK1);    TaskManager Codemanager = new TaskManager (tasks); Newthread (Codemanager). Start ();}

}

Success. Stop all the workers in the entire threadpoolexector and then add two more tasks to the queue again (note that there is no emptying, just a stop). This can be done in a timely manner, but one of the most deadly drawbacks is the ability to deal with tasks in time. Assume that you do not understand the task that threadpoolexecutor to run. There is no way to run these tasks again.


Custom thread pool
Stop delving into other people's stuff!

We are fully able to write our own threadpoolexecutor. Just expose the worker to it. This is not the beginning of the recall of the problem came, yes. Even if we can interrupt the thread directly, we can't start it again. What about clone a same thread line?
Thread
@Override
Protectedobject Clone () throws clonenotsupportedexception{
Throw Newclonenotsupportedexception ();
}
The answer is obvious. The thread does not support clone.

We need new one thread again to run again. In fact, we just need to replace the runnable in the original worker with our own task, and then let the access permission be properly released.

Also, let our customthreadpoolexecutor inherit thread, because it needs to monitor the running state of thread in all of its workers regularly.


Customthreadpoolexecutor
public class Customthreadpoolexecutor Extendsthreadpoolexecutor implements Runnable {
Public voidexecute (Testask command) {
....//change the Run interface to receive our business class
}
...
...
Private Final Class Worker
Extends Abstractqueuedsynchronizer
Implements Runnable
{
...
Testask Firsttask; Change Runnable to our business class for easy viewing status
...
Worker (Testask firsttask) {
...//identical to changing the initialization parameter to our business class
}

}
Public staticvoid Main (string[] args) {
Customthreadpoolexecutor pool = new Customthreadpoolexecutor (0, Integer.max_value,
60L, Timeunit.seconds,
Newsynchronousqueue ());

  testasktask = new Testask ();   Task.setinterval (1);    Pool.execute (Task);   Testasktask1 = new Testask ();   Task1.setinterval (2);    Pool.execute (TASK1); Newthread (Pool). Start ();} @Overridepublic Voidrun () {while (!           Thread.CurrentThread (). isinterrupted ()) {try {long current = System.currenttimemillis ();           set<testask> Toreexecute = new hashset<testask> ();            System.out.println ("\ t number is" + number);               for (Worker wrapper:workers) {testask tt = Wrapper.firsttask; if (TT! = null) {if (Current-tt.getlastexectime () > Tt.getinterval () * 5 * +) { 

Wrapper.interruptifstarted ();
Remove (TT);
if (tt.getfiles () = null) {
for (File file:tt.getFiles ()) {
File.delete ();
}
}
System.out.println ("THread is timeout:" + TT + "" + New Date ());
Toreexecute.add (TT);
}
}
}
if (toreexecute.size () > 0) {
Mainlock.lock ();
try {
for (Testask tt:toreexecute) {
Execute (TT),//execute this task again
}
} finally {
Mainlock.unlock ();
}
}
} catch (Exception E1) {
System.out.println ("Error happens when we trying to interrupt andrestart a Code task ");
}
try {
Thread.Sleep (500);
} catch (Interruptedexception e) {
}
}
}
}
Testask
class Testask implements Runnable {
.....

@Overridepublic voidrun() {    while(!Thread.currentThread().isInterrupted()) {       lastExecTime = System.currentTimeMillis();       System.out.println(Thread.currentThread().getName() + " is running-> " + new Date());        try {           CustomThreadPoolExecutor.number++;           Thread.sleep(getInterval() * 6 * 1000);           System.out.println(Thread.currentThread().getName() + " aftersleep");        } catch(InterruptedException e) {

Thread.CurrentThread (). interrupt ();
System.out.println ("interruptedexception happens");
}
}
System.out.println ("Going to die");
}
}
Finally the solution
In summary, the most secure is the use of the JDK threadpoolexecutor, assuming that the task in the pool of discretionary time control, can consider a comprehensive update, all aspects, 360 degrees without dead ends of the custom thread pool is certainly the best solution. However, it is important to pay attention to the processing of shared objects, and properly handle the methods of sharing objects.
In view of our scene. Because time is tight and there are not many tasks to understand. Temporarily selects all the policies that are updated again.

After the launch. Take the time to make your own custom threadpoolexecutor, then update up!

Java using the default thread pool trampled pits (iii)

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.