Java uses thread pool (Executorservice) To implement method timeout blocking with callable and future implementations

Source: Internet
Author: User

Today in the project development needs to use the implementation method plus time control, if the method executes too long to jump out of execution, nonsense does not say, directly on the code, with the thread pool with callable and the future way to execute the method of time-out blocking. I hope you guys correct me.


Enable thread pool          final Executorservice exec = Executors.newfixedthreadpool (1);          callable<map<string, string>> call =    new callable<map<string, string>> () {public              Map <string, String> call () throws Exception {                  map<string,string> excutemap = new hashmap<string,string& gt; ();                  Excutemap = Sendsshsys (Servicepc, arrport);//The corresponding business logic is executed here, note that the parameters used in the call are final                  return excutemap;}          };          Future<map<string, string>> future = Exec.submit (call);          try {              //20 seconds timeout, here is the return value of the call is taken out, if the time is still not completed, return null              map=future.get (timeunit.seconds);          } catch (Interruptedexception e) {          } catch (Executionexception e) {          } catch (TimeoutException e) {          }          //The map can be processed below. If map is null it means that execution time is too long and blocked.  


Java uses thread pool (Executorservice) To implement method timeout blocking with callable and future implementations

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.