TimeOut for Individual Threads in ExecutorService

Hello all,
I am using a FixedThreadPool to execute a number of individual jobs. The jobs are using an external chemistry library (CDK) to calculate various properties on a set of molecules. The problem is that for a small number of the molecules, this calculation does not terminate in a reasonable time. I'm not sure if it is a bug with the program or a property of the algorithm they are using or what. The problem is that once thread pool starts a number of these non-terminating jobs equal to the max pools, the entire pool is locked up on these non-terminating calculations, meaning the program comes to a standstill.
So what I need to do is terminate the jobs if they take longer than a TimeOut value. There doesn't seem to be a way to do this with the concurrency API - you can terminate the entire ExecutorService if it runs for too long, but not on an individual thread level, from what I can see. So how would I go about doing this?
Cheers,
nfitzgerald
String nstmt = new String("SELECT mol_id FROM " + infotablename + " WHERE XLogP IS NULL ORDER BY mol_id DESC");
          PreparedStatement stmt = con.prepareStatement(nstmt, ResultSet.TYPE_FORWARD_ONLY,
                    ResultSet.CONCUR_READ_ONLY);
          ResultSet rs = stmt
                    .executeQuery();
          ExecutorService pool = Executors.newFixedThreadPool(workers);
          while (rs.next()) {
               String mol_id = rs.getString("mol_id");
               pool.submit(new CalculationHandler(hostname, user, password, infotable, structable, mol_id));
          System.out.println("All Submitted.");
          pool.shutdown();
          pool.awaitTermination(36000, TimeUnit.SECONDS);
          pool.shutdownNow();

Is there anything wrong with doing it this way:
public class TimeOutWrapper implements Runnable {
     Runnable runnable;
     long timeout;
     public TimeOutWrapper(Runnable runnable, long timeout){
          this.runnable = runnable;
          this.timeout = timeout;
     public void run(){
          Thread thread = new Thread(runnable);
          thread.start();
          //check every .1 second to see if it is done, return if done
          for(int i = 0; i < (timeout/1000); i++){
               try {
                    Thread.sleep(1000);
               } catch (InterruptedException e) {
                    e.printStackTrace();
               if(!thread.isAlive()){
                    return;
          //if it makes it the whole timeout
          thread.interrupt();
     return;          
}And then setting up the pool like this:
ExecutorService pool = Executors.newFixedThreadPool(workers);
String mol_id = rs.getString("mol_id");
TimeOutWrapper timeOutJob = new TimeOutWrapper(new SomeRunnable(args),  30000);
pool.submit(timeOutJob);Is this a "bad" way of doing it? Am I breaking some law here, or is this a valid work-around?
Edited by: nfitzgerald on Aug 7, 2008 3:09 PM
Edited by: nfitzgerald on Aug 7, 2008 3:11 PM

Similar Messages

  • Set timeout for completion of each thread

    i have a requirement where i need to start n threads and set timeout for completion of each thread.
    if the thread is not executed successfully(because of timeout ) i have to enter in audit table that it failed because of timeout
    if executed successfully update audit table with success.
    can some one give me solution for this using ThreadPoolExecutor available jdk1.5

    Add a scheduled task to time out the task (when it would time out). Keep the Future and cancel it if the task completes successfully.
    final Future future = executor.schedule(new TimeoutTask(), timeoutMS, TimeUnit.MILLI_SECONDS);
    executor.execute(new Runnable() {
      public void run() {
          try {
             task.run();
          } finally {
             future.cancel(true);
    });

  • How to add timeout for threads which are running  using ThreadPoolExecutor

    I am trying change my existing functionality with ThreadPoolExecutor. I was unable to achieve fully.
    Here is my issue.
    I was creating multiple threads for independent DB update operations. And was calling join with time value on the each thread, for any reason if the db update hangs so that thread should die.
    Now am trying use a nice ThreadPoolExecutor so that it can run and queue the threads nicely. But how do I create the timeout values for the threads which are in the ThreadPool. For any reason if the thread hangs then timeout will take care of killing the thread. When we use execute method submit the runnable task its not guaranteed that thread will run immediately. So when the executor will execute the submitted task is not know.
    Probably I might be wrong some where.
    Thanks.

    Future task = threadPoolExecutor.submit(...);
    //this will block until it finishes or times out.
    task.get(REQUEST_TIMEOUT, TimeUnit.MILLISECONDS);

  • Set request timeout for distributed cache

    Hi,
    Coherence provides 3 parameters we can tune for the distributed cache
    tangosol.coherence.distributed.request.timeout      The default client request timeout for distributed cache services
    tangosol.coherence.distributed.task.timeout      The default server execution timeout for distributed cache services
    tangosol.coherence.distributed.task.hung      the default time before a thread is reported as hung by distributed cache services
    It seems these timeout values are used for both system activities (node discovery, data re-balance etc.) and user activities (get, put). We would like to set the request timeout for get/put. But a low threshold like 10 ms sometimes causes the system activities to fail. Is there a way for us to separately set the timeout values? Or even is it possible to setup timeout on individual calls (like get(key, timeout))?
    -thanks

    Hi,
    not necessarily for get and put methods, but for queries, entry-processor and entry-aggregator and invocable agent sending, you can make the sent filter or aggregator or entry-processor or agent implement PriorityTask, which allows you to make QoS expectations known to Coherence. Most or all stock aggregators and entry-processors implement PriorityTask, if I correctly remember.
    For more info, look at the documentation of PriorityTask.
    Best regards,
    Robert

  • Timeout for  "new BufferedReader (new InputStreamReader (System.in));"

    BufferedReader in = new BufferedReader (new InputStreamReader (System.in));
    String message = in.readLine();  The above code waits infinitely until the user enter the data from the command line and presses enter key.
    The following code can provide a timeout to the above waiting (it works fine).
    But is there a SIMPLER WAY to provide timeout for above waiting, something like setSoTimeout(int milliseconds) method in DatagramSocket, Socket and ServerSocket classes*?*
    http://www.coderanch.com/t/232213/threads/java/implement-timeout-threads
    =>
    import java.util.Timer;  
    import java.util.TimerTask;  
    import java.io.*; 
    public class test{  
    private String str = "";  
         TimerTask task = new TimerTask(){  
                 public void run(){  
              if( str.equals("") ){  
                   System.out.println( "you input nothing. exit..." );  
                   System.exit( 0 );  
         public void getInput() throws Exception{  
              Timer timer = new Timer();  
              timer.schedule( task, 10*1000 );  
              System.out.println( "Input a string within 10 seconds: " );  
              BufferedReader in = new BufferedReader(  
                   new InputStreamReader( System.in ) );  
              str = in.readLine();  
              timer.cancel();  
              System.out.println( "you have entered: "+ str );   
         public static void main( String[] args ){  
              try{  
                   (new test()).getInput();
              }catch( Exception e ){  
                   System.out.println( e );  
              System.out.println( "main exit..." );  
    }

    No. System.in doesn't have a timeout API. Sockets do.

  • IOS 8 - contact's responses to a group message where I am included being placed in individual thread as opposed to the group thread?

    Has anyone experienced this issue?  Here's an example of what is happening:
    A group message is initiated by my friend that includes myself and 2 Android users.  All of us have group messaging turned on.
    Replies from one of the Android users do not get included in the group thread, but in that person's individual thread within Messages.  The other user's replies are included in the group thread.  My replies are also included in the group thread.
    If I turn off iMessages within the settings menu, the replies from the Android user that were previously going into the individual thread now are included within the group thread.  If I turn back on iMessages, the replies are separated again whenever they are sent, but only from the one Android user.
    Is this a problem with the way the iPhone handles group SMS/MMS messages, or is it an issue with my friend's Android device settings?  What makes me think it's an issue on my end is that things work as intended if I turn iMessages off.
    Thanks in advance for any help!

    Hi,
    In Group chats in iMessages it seems the iMessages server will not allow you to switch the ID being used for one of the contacts (there is no way to tell if the other people in the group chat know this info and whether the Contacts wants it to be known - at least that is the presumption).
    If you want to use his iPhone number then you will have to start a new Chat.
    If his Apple ID is on  his iPhone and of course on his Mac then it can be the case that iMessages will "offer" the pop ups to enable the ID again.
    I find they arrive when I want to do something else and I have to almost dismiss them  to proceed.
    I find that this will activate a Second Apple ID on a second iPhone or the second iPhone number will suddenly appear Active on the Mac's settings for the iMessages account.
    8:16 pm      Sunday; June 29, 2014
    ​  iMac 2.5Ghz i5 2011 (Mavericks 10.9)
     G4/1GhzDual MDD (Leopard 10.5.8)
     MacBookPro 2Gb (Snow Leopard 10.6.8)
     Mac OS X (10.6.8),
     Couple of iPhones and an iPad

  • Wait for all threads in a array to die

    I everyone. I'm from Portugal and I have some experience in JAVA programming (approximately five years) but this is the first the first time that i'm trying to use threads. I'm trying to learn writing some simpler code that does almost exactly at the basic level the same stuff that a complex application that I need to write for my work.
    What I'm trying to do is execute a counter that counts all operations in threads belonging to the same array (an array of n threads).
    A static variable in the Thread class (implementing Runnable) counts all operations performed by all threads and sums them all and shoud display the total of operations after all threads terminate, but this exactly what I don't know how to do:
    This is my example code:
    public class TT1 implements Runnable {
         int id;
         double last_number;
         static int threads_counter = 0;
         static int total_threads = 4;
         static long total_numbers;
         int total_randoms = 1000;
         public void run() {
              for (int i=0;i<total_randoms;i++)
                   total_numbers++;
                   // does some stuff, in this case, generate a random number!
                   last_number = Math.random();
              System.out.printf("Thread %d:%f(%d)\n",id,last_number,total_numbers);
         public TT1() {
              id = threads_counter++;
              new Thread(this).start();
         public static void main(String[] args) {
              // TODO Auto-generated method stub
              Thread [] threads = new Thread[total_threads];
              for (int i=0;i<threads.length;i++)
                   threads[i] = new Thread(new TT1());
              /* commented code using join(), is not working or I don't know
              how to use it! */
              for (int i=0;i<threads.length;i++)
                   try {
                        threads.join();
                   } catch (InterruptedException e) {
                        e.printStackTrace();
              try {
                   threads[total_threads-1].join();
              } catch (InterruptedException e) {
                   e.printStackTrace();
              // this line should be executed ONLY after ALL threads have died!
              System.out.println("******GENERATED NUMBERS TOTAL:" + total_numbers);
    Somebody can give me a hint how to solve this ?

    Thanks for your replies.
    Actually, i've corrected the code, now i'm starting the threads outside the constructor. Originally I thought this could be a simpler way to create the threads: launching them at same time I'm creating them! Is this wrong ? :) Well, watching the results.
    I changed my code:
    public class TT1 implements Runnable {
         int id;
         double last_number;
         static int threads_counter = 0;
         static int total_threads = 4;
         static long total_numbers;
         int total_randoms = 1000;
         public void run() {
              for (int i=0;i<total_randoms;i++)
                   total_numbers++;
                   // does some stuff, in this case, generate a random number!
                   last_number = Math.random();
              System.out.printf("Thread %d:%f(%d)\n",id,last_number,total_numbers);
         public TT1() {
              id = threads_counter++;
         public static void main(String[] args) {
              // TODO Auto-generated method stub
              Thread [] threads = new Thread[total_threads];
              /* create individual threads */
              for (int i=0;i<threads.length;i++)
                   threads[i] = new Thread(new TT1());
              /* launch the threads (NEW CODE) */
              for (int i=0;i<threads.length;i++)
                   threads.start();
              /* commented code using join(), is not working or I don't know
              how to use it! */
              for (int i=0;i<threads.length;i++)
                   try {
                        threads[i].join();
                   } catch (InterruptedException e) {
                        e.printStackTrace();
              // this line should be executed ONLY after ALL threads have died!
              System.out.println("******GENERATED NUMBERS TOTAL:" + total_numbers);
    And I obtain the output:
    $ java TT1
    Thread 0:0,191546(1000)
    Thread 1:0,937476(2000)
    Thread 2:0,825079(3000)
    Thread 3:0,451367(4000)
    ******GENERATED NUMBERS TOTAL:4000Exactly as I want it!
    All is good when it works good ;)
    Best regards

  • How to avoid a timeout for a long-running query

    Hello,
    in my application I insert some rows in a temporary table on submit in a PL/SQL block on the page 1. Then I read these rows from the table on the page 2. Unfortunately the insert takes too long time, because I also have to make some other SELECTs etc in that block. That's why the application hits the Apache timeout for mod_plsql and HTTP error between pages 1 and 2.
    I have found some threads about this topic in this forum. There are some suggestions with meta refresh tag etc. I understand, that I have to implement some kind of processing page between the pages 1 and 2 to show a waiting message etc. But I could not find any ready "cook book" for such implementation.
    Could you please help me?
    Thanks in advance
    Andrej
    P.S. This application don't use AJAX code, so I would prefer a solution without AJAX.

    Hello Chris,
    I am not sure, how to implement this approach. So I would start on the page 1 a job (dbms_scheduler or dbms_job), which would create a temporary table in the background. The application should branch to the page 3 with a message "Please wait...". I have to poll the results of the job and branch to the page 2, when the job is ready and I can select from the created temporary table. So far I like this way very much.
    Could you please give me more details about the page 3 (polling page)? I have the following questions now:
    1. I assume I have to set the meta refresh tag on this page. But in which PL/SQL block can I poll for the running job (on load process?).
    2. How can I branch from this page to another page? If I only use refresh tag, how can I branch to another page only on the special condition (ready flag)?
    Thanks in advance
    Andrej

  • Group/mass messaging into individual thread

    hello
    was wondering if there was a way to send group/mass text and then make the messages go to each contact's individual thread?
    I also turned off group messaging because then everyone gets a response when one person replies, and not everyone likes that. i want a way to send a mass text w/o going to each individual's thread.
    thanks

    IMessage is currently down and is acting up.
    I suggest for now, you dont use group IMessage.
    There is also a possibility that one of your devices your trying to talk to has a bug...
    If IMessage doesnt work by Thursday, I would give Apple a call

  • Error: Timeout for content (ias1.0.2.2 on W2000)

    I have recently installed iAS 1.0.2.2 (standard edition)
    Database is 8.1.7.1.1
    OS is Windows 2000
    Machine is Compaq Armada M700 with 512Mb memory
    The install seemed to go fine, but some of the Portal administrative portlets are displaying the message "Error: Timeout for content" (e.g. instead of the "Services" portlet). Different portlets timeout each time I refresh the page. The machine appears to be healthy. iAS and the database are the only Oracle software installed. The 81711 patch was applied after the original iAS installation in the hope of fixing the problem. Portal proxy configuration has not been changed.
    I've tried a couple of changes in the zone.properties file without success e.g.
    servlet.page.initArgs=stall=30
    servlet.page.initArgs=requesttime=1000
    Jserv.log has errors like this:
    [01/06/2001 14:24:54:993 BST] page/JNI: Exception when trying to connect in 1.
    [01/06/2001 14:24:54:993 BST] page/Timeout occurred, label=27 url=http://MYHOST.MYDOMAIN:7778/pls/portal30/!PORTAL30.wwpro_app_provider.execute_portlet
    [01/06/2001 14:24:54:993 BST] page/ContentFetcher Unexpected Exception, name=content-fetcher20
    java.net.SocketException: connect (code=10061)
    at java.net.PlainSocketImpl.socketConnect(Native Method)
    at java.net.PlainSocketImpl.doConnect(PlainSocketImpl.java:313)
    at java.net.PlainSocketImpl.connectToAddress(PlainSocketImpl.java:133)
    at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:120)
    at java.net.Socket.<init>(Socket.java:269)
    at java.net.Socket.<init>(Socket.java:125)
    at HTTPClient.HTTPConnection$EstablishConnection.run(HTTPConnection.java, Compiled Code)
    Has anyone encountered similar, or can anyone suggest a solution?
    Regards, Mark
    null

    Futher to previous thread, I've just tried reinstalling on a clean database 8.1.7.1.1 EE (no invalid objects) as per release notes, and I'm still suffering the same "Timeout for content" in random portlets. Could it be a Windows 2000 issue (I'm running SP 1 as per release notes)? Or maybe something to do with the fact that the hostname has uppercase letters in it?
    Jason suggested a proxy issue, but I haven't made any changes there - not even gone into that portlet.
    Any advice would be greatly appreciated.
    As an alternative, when will Linux 1.0.2.2 be available?
    Regards, Mark
    null

  • Setting a timeout for HttpConnection?

    Hi,
    Is there any way to set a timeout for an HttpConnection instance? I've got something like:
    HttpConnection conn = (HttpConnection)Connector.open("www.mysite.com");
    but the timeout on my particular device waits 2 minutes! I'd like to make it something more like 20 seconds. Any way to do this?
    Thanks

    I am surprised that HttpConnection doesn't have a way to timeout already. I searched thru the docs and I cant find any.
    Anyway this is my solution. Use a Thread. Start the thread before calling Connector.open. In the run method of the thread, sleep for 20 secs, wake up and display something to the user. This is assuming that your Connector.open is not blocking. i.e its in a thread of its own. this is an example of a non-blocking httpconnection
      public void commandAction(Command c, Displayable s) {
            if (c.getLabel().equals("GET")) {
                final MIDlet middy = this;
                new Thread() {
                    public void run() {
                        try {
                            //make your http connection here.
                            HttpConnection conn = (HttpConnection)Connector.open("www.mysite.com");
                        } catch (Exception ie) {
                            ie.printStackTrace();
                }.start();
        }of course there are other ways to do that. just my suggestion

  • Timeout for cfstoredproc

    Hi. Is there a way to set timeout for the tag
    <CFSTOREDPROC>? I mean, for cfquery, it has a parameter
    timeout in seconds. How about for CFSTOREDPROC?
    I tried using
    <cfset startproc = GetTickCount()>
    <cfsetting requesttimeout = "20" />
    <CFSTOREDPROC PROCEDURE="fsdfsd" DATASOURCE="sfsds">
    cfprorparams here.........
    </CFSTOREDPROC>
    <cfset proc_execute = GetTickCount() - startproc >
    proc_execute returns about 30,000 ms which is 30 s. But the
    timeout needs to end it in 20 s. It seems requesttimeout doesn't
    include the time it took for the stored procedure executing. That
    is why I'm looking for a timeout in cfstoredproc. Any suggestions?
    I don't wanna go to the Oracle server and set the timeout settings.
    I want it done in Coldfusion. Thanks.

    There is no timeout attribute for cfstoredproc. Since all the
    processing is occurring inside the database there is no way for us
    to time it out. Also, since we do not know the DBMS in advance we
    could not use any DBMS specific means. If Oracle SQL lets you set
    it inside the SP, that is your way to go.
    RequestTimeout/page timeouts only cover the time CF is in
    control of the thread.

  • Error: Timeout for content=#number#

    RDBMS 8.1.6.3.
    Sun solaris 2.6
    My previous installation was OAS9i 1.0.2.0 with portal 3.0.6.x
    Then yesterday I installed the OAS9i 1.0.2.2 (the runInstaller chose what software had to be deleted, upgraded or installed as new) and I upgraded the portal schemas with the script found here in OTN.
    The whole process seemed all ok, but now when I access to the main portal page usually have the error in subject in the place of every portlet. Sometime the error is "Error: The portlet could not be located".
    I think both are related to the upgrade process, but I checked the upgrade log produced by the script and found only errors about installing/upgrading Intermedia, but for me it is normal, as I have never installed it.
    Does someone have suggestions/comments?
    Thanks
    Mauro
    null

    Hi all
    First of all, I want to thank you for your suggestions.
    Then I would inform you about my progress.
    Following Hyundeok's suggestion (I don't use SSL), I checked the jserv.log and I found these errors:
    1) Repository /pandorino_home/3rdsw/oradba/product/OAS9I/Apache/Jserv/servlets/Parallel.jar doesn't exist!
    2) page/JNI: Exception when trying to connect in 1.
    page/Timeout occurred, label=510 url=http://pandorino:7777/pls/dad_portal/!WWW_PORTAL.wwpro_app_provider.execute_portlet
    page/ContentFetcher InterruptedIOException Caught, Fetcher Timedout name=content-fetcher5
    3) (EMERGENCY) ajp12: ping: no reply (0) Please make sure that the wrapper.classpath is pointing to the correct version of ApacheJServ.jar
    (EMERGENCY) ajp12[1]: cannot scan servlet headers (500)
    (ERROR) an error returned handling request via protocol "ajpv12"
    (ERROR) an error returned handling request via protocol "balance"
    4) page/UncaughtException in thread name=content-fetcher2, starting a new fetcher after exception java.lang.ThreadDeath
    My comments/actions:
    About (1), very strange, the Parallel.jar file doesn't exist! But I don't think that
    it is related to the error in subject. In any case this error is raised only at Apache startup.
    About (2), when it occurs, I see the error "Error: Timeout for content=#number#" in the place of portlet.
    following Randy's suggestion, I increased the timeout of:
    (-) "Login Server" portlet provider (from 10 to 20 seconds),
    (-) "Oracle Report Security" portlet provider (from 1(one) to 20 seconds),
    (-) "Monitor" portlet provider (from 10 to 20 seconds).
    About (3), I increased the timeout in the jserv.conf file: ApJServVMTimeout 20
    About (4), when it occurs, I see the error "Error: The portlet could not be contacted" in the place of portlet.
    No action performed.
    After a week of tests, It seems that (2) and (3) have been fixed thanks to the increased timeout.
    Concerning (4), it is still experienced by me and other users. I think that in this case the
    last thing to try is to apply the patch fix suggested by John.
    But at the moment I don't have time to do this, so in the meantime I will press the browser's "reload" button until the portlet is displayed.
    Thanks again.
    Mauro

  • I add a timeout for InputStream read().

    I am looking for a timeout for InputStream read() since Java doesn't support it. I use a Timer class to handle the timeout value and put the InputStream.read() into another thread. When the time is up, the Timer object will stop the thread of reading. What do you think about this solution? Do you have any other better solution?
    thanks

    and any ideas on how to stop this blocking read() method from an InputStream (Java 5)???? When googling on this topic I find an incredible amount of questions on this subject BUT no solutions. What to do?? I'm a little bit affraid it comes down to hacking the JVM finding the Thread in some memory block and removing it with brute force.
    hmmm when I think of it, it's really driving my crazy.... the only thing I can think of is throwing my PC out of the window and buy a new one. Unfortunately there's no budget for that it will cost to many PCs :-)
    Edited by: R_e_n_s on Jun 3, 2008 6:45 AM

  • How to configure session timeout for SAP Netweaver Portal

    Hi,
    I would like to know the way to configure the session timeout for SAP Netweaver Portal.

    Hi Kim,
    the solution for your question  is in this thread.
    500 Connection timed out
    if it is helpful award me points.
    Regards,
    R.Suganya.

Maybe you are looking for

  • I cannot open any Word document or even Powerpoints or anything related to Office 2008, which has been working fine for the last 2 years. I need help...

    I installed an application called "You SendIt" because some audio files were sent to me and I had to access them through it. My Mac is running Windows and OS-X. I bought an version of Office 2008 separately. I tried to uninstall it, to get rid of all

  • Setting timeout of web service client

    I created a web service client using the java proxy for a web service by running my web service in weblogic workshop test browser and by using the jar file created by clicking on "Java Proxy" button. i am calling my web service my adding code similar

  • Error in Installing RCU for Oracle Webcenter Content Imaging

    Hi, I am comming across this error while installing RCU for Oracle Webcenter Imaging with Mircosoft SQL 2005 as the backend database. I am pasting the IPM.log file below which shows the error during the installation. Please help me from this. JDBC SQ

  • Error code mem_/2/5

    Hi, I have this error code on my Imac G3 and no software will open without immediately crashing - any advice? Do I need to get a new memory stick? I noticed there were other questions regarding an error code mem_/2/4 - is this the same problem?

  • Third party program

    hi all im totally new to this forums and im learning active directory im using 2008 version of AD with more than 60 clients computer member of this ad domain everything works fine including gpo but i have a big problem. in accounting department they