JAVA processing line blocks until those when __java

Source: Internet
Author: User

In the actual business, it is multithreaded and open business, often encountered a thread execution timeout. Programs that do not capture this type of situation can cause the program to remain in the waiting state, affecting subsequent threads to run.
For example, network communication, a complex database query under a single task, which typically deals with such issues, enables a background daemon to monitor whether the execution of a user thread (business thread) is timed out, or if the timeout is not waiting, usually before the user thread's. Start () method is invoked. Invokes the start () method of the daemon and passes the timeout to the daemon. In the daemon thread's Run () method, The Sleep () method is performed, the hibernation time is long, and a synchronized variable is used in the daemon to store the user's thread timeout. In the user thread, after the program executes, the shouldered thread is invoked to change the synchronization variable. After the daemon thread sleep () method, to determine whether the value of the synchronization variable has changed, if not changed, that the user thread has not swept the line completed, that is, timeout. However, this method does not interrupt the user thread.
In addition, there is a way to interrupt the user thread does not continue to run, the use of java.util.concurrent the following interface, class can also be completed. Here is an example. Java code   import java.util.concurrent.callable;   import  java.util.concurrent.executionexception;   import java.util.concurrent.executorservice;    import java.util.concurrent.executors;   import java.util.concurrent.future;    import java.util.concurrent.timeunit;   import java.util.concurrent.timeoutexception;       public class timeout {       public  Static void main (String[] args) {           int  timeout = 2; //sec .            Executorservice executor = executors.newsinglethreadexecutor ();            boolean result = false;              Future<Boolean> future =  Executor.submit (new myjob (Request parameters));//  submit the task to the thread pool                try {                   result = future.get (Timeout*1000, timeunit.milliseconds);   set to be completed in 200 millisecond time                  SYSTEM.OUT.PRINTLN (Result);           } catch  ( Interruptedexception e)  {              &NBSP;&NBSP;SYSTEM.OUT.PRINTLN ("Thread interrupt error. ");               future.cancel (TRUE);//   Interrupt Threads               }& to perform this tasknbsp;catch  (executionexception e)  {            &NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;SYSTEM.OUT.PRINTLN ("Thread service error.") ");               future.cancel (TRUE);//   Interrupt Threads               } catch to perform this task   (timeoutexception e)  {//  Timeout exception             &NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;SYSTEM.OUT.PRINTLN (timeout). ");                   Future.cancel (True);//  interrupts the thread that performed this task                }finally{                SYSTEM.OUT.PRINTLN ("Thread service shutdown.") ");              &Nbsp;executor.shutdown ();           }        }              static class  myjob implements callable<boolean> {              private String t;            public myjob (string temp) {                this.t= temp;           }           public boolean call ()  {                   for (int i=0;i<999999999; i++) {                    if (i==999999997) {                        system.out.println (t);                    }                    if  (thread.interrupted ()) { //is important                         return false;                       }                }                 system.out.println ("Continue to execute ...");                   return true;               }          }   } 


When I do socket communication, my side of the server needs to set the timeout program (the client for the hardware terminal connection, no response within a few minutes to set the timeout program)

This socket server starts with the TimerTask type, starts and then opens dozens of more threads to handle the terminal connection ...

I tried two kinds of timeout programs are good: one is through the thread join settings, one is through the concurrent future means

Join

public class ThreadTest {
public static void Main (string[] args) {
Counterthread ct = new Counterthread ();
Ct.start ();
try {
Ct.join (20000); Time of timeout, such as 20 seconds
if (ct.isalive ()) {//description is not completed within the time set, timeout
Ct.interrupt ();
throw new TimeoutException ();//thrown to terminate the socket thread
}
Ct.getresult ()//normally can get the value after execution
catch (Interruptedexception e) {
E.printstacktrace ();
}
}
}
Class Counterthread extends Thread {
Public counterthread (int time) {
constructor, passing some useful values to run;
}
private int result;

public int GetResult () {//result value obtained on above
return result;
}
public void Run () {
result = a task performed, such as reading client data;
}
}
Furture:

public class TimeoutTest1 {

public static void Main (string[] args) {
Final Executorservice service = Executors.newfixedthreadpool (1);

Taskthread taskthread = new Taskthread ();
SYSTEM.OUT.PRINTLN ("Submit task ... begin");
future<object> taskfuture = Service.submit (Taskthread);
SYSTEM.OUT.PRINTLN ("Submit task ... end");
try {
Object re = taskfuture.get (6000, timeunit.milliseconds);//timeout setting, 6s
System.out.println (re);
catch (Interruptedexception e) {
E.printstacktrace ();
catch (Executionexception e) {
E.printstacktrace ();
catch (TimeoutException e) {
SYSTEM.OUT.PRINTLN ("Timeout cancel task");
Taskfuture.cancel (TRUE);
SYSTEM.OUT.PRINTLN ("Timeout cancel task ok");
finally {
Service.shutdown ();
}

}

}

Class Taskthread implements Callable<object> {

Public Object Call () throws Exception {
String result = "Null results";
try {
System.out.println ("task begins ...");
Thread.Sleep (5000);
result = "correct results";
System.out.println ("End of Task ...");
catch (Exception e) {
System.out.println ("Task is interrupted!");
}
return result;
}

}

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.