How handling Threads with a specific timeout

Hi all,
first - sorry for my english - i hope you get my problem
I have the following issue:
I have a bunch of threads which take their time. But I want to limit their time and so use a timeout. So e.g. I want to say that all threads have to be finished after 30s, otherwise they will be interrupted/shutdown or whatever.
I had a look at the Executor and ExecutorCompletionService which I actually think they are cool.
But if I use the pull method with a timeout 30sec - doesnt it work like that:
1. try to get the first finished task - wait up to 30secs
2. after getting the result from the first task or after waiting 30secs - try to get another result or wait 30secs
3. after that - again get the next result or wait 30secs.
so actually I could wait for some minutes untill every thread is finished because I always wait up to 30secs.
So my question is - how can I realise, that after 30secs the threads are finished somehow... is this possible via the concurrency package or has it coded differently ?
Thanks
andreas

Hi,
It is not possible to inform the Thread that it has to expire after certain time. When the Thread starts, there can be a loop condition inside the run() method which control some boundary conditions as in the previous post
Take a look at the below classes it may give you some ideas?
There is another possible way if you take a look at Process as a sample below which may help
public static synchronized Process exec(String command, String[] envp, long interval, long timeout)
     throws IOException, InterruptedException
          Process     process = null;
          if (null == envp)
               process = Runtime.getRuntime().exec(command);
          else
               process = Runtime.getRuntime().exec(command, envp);
          return processTimeout(process, interval,timeout);
     } // exec
private static synchronized Process processTimeout(Process process, long interval, long timeout)
     throws InterruptedException
          long     time_waiting = 0;
          boolean     process_finished = false;
          while (time_waiting < timeout &&
                  !process_finished)
               process_finished = true;
               try
                    Thread.sleep(interval);
               catch (InterruptedException e)
                    e.fillInStackTrace();
                    throw e;
               try
                    process.exitValue();
               catch (IllegalThreadStateException e)
                    // process hasn't finished yet
                    process_finished = false;
               time_waiting += interval;
          if (process_finished)
               return process;
          else
               process.destroy();
               return null;
     } // processTimeout
// what about the bloew it may give you an idea!!!!!!!!!!!!!!
public class Timeout
private long _duration;
    private long _now;
    private Task _head;
    public static class Task
        public void unlink()
            _next._prev = _prev;
            _prev._next = _next;
            _next = _prev = this;
            _timeout = null;
            _expired = false;
        public void setNext(Task task)
            if(_timeout == null || task._timeout != null && task._timeout != _timeout || task._next != task)
                throw new IllegalStateException();
            } else
                Task next_next = _next;
                _next._prev = task;
                _next = task;
                _next._next = next_next;
                _next._prev = this;
                _next._timeout = _timeout;
                return;
        public void schedule(Timeout timer)
            unlink();
            timer.schedule(this);
        public void schedule(Timeout timer, long delay)
            unlink();
            timer.schedule(this, delay);
        public void reschedule()
            Timeout timer = _timeout;
            unlink();
            timer.schedule(this, _delay);
        public void cancel()
            _timestamp = 0L;
            unlink();
        public boolean isExpired()
            return _expired;
        public void expire()
        private void doExpire()
            synchronized(this)
                _expired = true;
                expire();
        Task _next;
        Task _prev;
        Timeout _timeout;
        long _delay;
        long _timestamp;
        boolean _expired;
        public Task()
            _timestamp = 0L;
            _expired = false;
            _next = _prev = this;
    public Timeout()
        _head = new Task();
        _head._timeout = this;
    public long getDuration()
        return _duration;
    public void setDuration(long duration)
        _duration = duration;
    public void setNow()
        _now = System.currentTimeMillis();
    public long getNow()
        return _now;
    public void setNow(long now)
        _now = now;
    public Task expired()
        long _expiry = _now - _duration;
        if(_head._next != _head)
            Task task = _head._next;
            if(task._timestamp > _expiry)
                return null;
            task.unlink();
            synchronized(task)
                task._expired = true;
            return task;
        } else
            return null;
    public void tick()
        long _expiry = _now - _duration;
        do
            if(_head._next == _head)
                break;
            Task task = _head._next;
            if(task._timestamp > _expiry)
                break;
            task.unlink();
            try
                task.doExpire();
            catch(Throwable th)
                Log.warn("EXCEPTION ", th);
        } while(true);
    public void schedule(Task task)
        schedule(task, 0L);
    public void schedule(Task task, long delay)
        if(task._timestamp != 0L)
            task.unlink();
            task._timestamp = 0L;
        task._expired = false;
        task._delay = delay;
        task._timestamp = _now + delay;
        Task last;
        for(last = _head._prev; last != _head && last._timestamp > task._timestamp; last = last._prev);
        last.setNext(task);
    public void cancelAll()
        _head._next = _head._prev = _head;
    public boolean isEmpty()
        return _head._next == _head;
    public long getTimeToNext()
        if(_head._next == _head)
            return -1L;
        } else
            long to_next = (_duration + _head._next._timestamp) - _now;
            return to_next >= 0L ? to_next : 0L;
    public String toString()
        StringBuffer buf = new StringBuffer();
        buf.append(super.toString());
        for(Task task = _head._next; task != _head; task = task._next)
            buf.append("-->");
            buf.append(task);
        return buf.toString();
} // TimeOutI hope this can assist in a further step to solve your problem
Have a nice day
Alan Mehio
London, UK
Edited by: alan_mehio on Oct 10, 2007 9:30 AM

Similar Messages

  • How handle Master with dynamic Detail

    Hello!
    I have the following issue and will explain it on a little example:
    I have one "invoice"-object and many "invoiceitems"-objects in a collection (classic master - detail).
    I must dynamically set the where and ordering - clause for the invoiceitems.
    How can i do this or what is the best practice for this issue?
    best regards
    Harald.

    The TopLink Collection mappings support ordering, and you can also control exactly how members of the Collections are selected. However, if the contents of a Collection depend on some external characteristic (other than the identity of the Collection's owner), then it sounds like you need to manage this Collection manually (ie have the parent Object query for it's child Objects using some parameterized query and some context sensitive set of arguments).
    If you want an Object to "automatically" build a Collection then you need a sure fire way of determining what the contents of that Collection are going to be from information contained in the parent Object.

  • How do I search threads within a specific support community, i.e.. Apple Remote Desktop?

    Very frustrated with new layout of discussion forums...
    How do I search key words within threads within a specific support community?
    For Example I want to search the phrase 'couldn't collect' within the Apple Remote Desktop community.

    Thanks for your response. I'm well aware of the global search field.
    My problem with that is if I search the term 'couldn't collect', (in reference to a very specific Error message generated while running a report via Apple Remote Desktop Task Server) I get a slew of useless hits that have either the words 'couldn't' and/or 'collect' or any variation of those words, such as 'collection'.
    I'm looking for responses that are very specific to Apple Remote Desktop only. I don't have hours to weed through thousands of responses that have no bearing to that at all.
    Searching within specific sub-communities was possible before this new layout. Whatever happened to the booelean searches and searching by phrases and the 'advanced' searches? Do they still exist?

  • How to deal with session timeouts?

    How to deal with session timeouts?
    With our current configuration of using single signon, when the web session times out (currently 20 minutes of inactivity), the user loses anything they have entered on a service form.  The use case is that a user starts filling out a form and gets interrupted, goes to lunch, etc, returns and spends time filling out the form (in the mean time the web session has timed out).  When they try to submit the service they get re-logged in through SSO and they have lost all of their entries in the service.   This creates some very unhappy users.
    I'd like to know how long other customers set their web session timeouts to and if anyone has come up with ways of handling this situation - either through somehow re-establishing the session or through warnings to the user about how long they have to complete a form.

    Hi,
    The timeout period for HTTP sessions that are created in the corresponding Web application. After being inactive for the specified timeout, the HTTP sessions expire. The period is specified in minutes:
    <!ELEMENT session-timeout (#PCDATA)>
    You can only change the session timeout property in the applicationu2019s own deployment descriptors. This is not possible for the Global Web Descriptor.
    following may help you:
    [Additional Configuration Settings |http://help.sap.com/saphelp_erp2005vp/helpdata/en/a9/7a9602ad094b82a293f06d1cbe2c14/frameset.htm]
    Regards,
    Sahidur

  • How to handle dbms_xmldom with no data values.(no_data_found error in dom)

    hi,
    i have below block,
    DECLARE
    doc dbms_xmldom.DOMDocument;
    node dbms_xmldom.DOMNode;
    elem dbms_xmldom.DOMElement;
    cur_node dbms_xmldom.DOMNode;
    root_elem_data dbms_xmldom.DOMElement;
    root_elem_tab dbms_xmldom.DOMElement;
    root_node_data dbms_xmldom.DOMNode;
    mode_elmn dbms_xmldom.DOMElement;
    mode_node dbms_xmldom.DOMNode;
    mode_text dbms_xmldom.DOMText;
    doc1 DBMS_XMLDOM.DOMDOCUMENT;
    root_node_data1 DBMS_XMLDOM.DOMNODE;
    child_document DBMS_XMLDOM.DOMDOCUMENT;
    child_rootnode DBMS_XMLDOM.DOMNODE;
    V_CLOB CLOB;
    v_doc CLOB;
    v_EMP CLOB;
    v_output_filename VARCHAR2(300) := 'SPOOL_DIR/'||'EMP_XML_FILE.xml';
    l_xmltype XMLTYPE;
    BEGIN
    doc := dbms_xmldom.newDOMDocument;
    node := dbms_xmldom.makeNode(doc);
    dbms_xmldom.setversion(doc, '1.0');
    dbms_xmldom.setCharset(doc, 'UTF8');
    elem := dbms_xmldom.createElement(doc, 'PartnerInfo');
    dbms_xmldom.setAttribute(elem,'xmlns','EMP');
    cur_node := dbms_xmldom.appendChild(node, dbms_xmldom.makeNode(elem));
    mode_elmn := dbms_xmldom.createElement(doc, 'EMPLOYEE');
    mode_node := dbms_xmldom.appendChild(cur_node,dbms_xmldom.makeNode(mode_elmn));
    BEGIN
    SELECT value(e) INTO l_xmltype
    FROM TABLE(XMLSequence(Cursor(SELECT * FROM EMP1 where EMPNO=7501))) e;
    child_document := DBMS_XMLDOM.newDOMDocument(l_xmltype);
    root_node_data1 := dbms_xmldom.importNode(doc,dbms_xmldom.makeNode(dbms_xmldom.getDocumentElement(child_document)),TRUE);
    root_node_data1 := DBMS_XMLDOM.appendChild(root_node_data, root_node_data1);
    EXCEPTION
    WHEN OTHERS THEN
    Dbms_Output.Put_Line('Error in SELECT stmt(UC_PARTNER_MS):::'||'error::'||SQLERRM);
    END;
    dbms_lob.createtemporary(v_doc, true);
    dbms_xmldom.writeToClob(doc,v_doc,'UTF8');
    v_EMP:= v_doc;
    dbms_xmldom.writeToFile(DOC,v_output_filename,'UTF8');
    dbms_xmldom.freeDocument(doc);
    --Dbms_Output.Put_Line('THE OUTPUT IS::'||V_EMP);
    EXCEPTION
    WHEN OTHERS THEN
    Dbms_Output.Put_Line('Error in SELECT stmt(UC_PARTNER_MS):::'||'error::'||SQLERRM);
    END;
    The xml file is 'EMP_XML_FILE.xml'
    <empno>U++kYmcVuGchxbh+++++++++++++++1+</empno>
    <empname>J</empname>
    suppose the empno 7501 is not available in our emp table,
    i got error
    ORA-03113: end-of-file on communication channel
    how to handle xmldom with no data values.
    by
    siva

    hi,
    please give the solution
    by
    siva

  • I installed Mountain Lion so that I could sync my notes with my iPhone that already syncs notes with a specific email address I use for school, but during the install it automatically set up Notes to sync w the wrong email addy. How can I fix it?

    I installed Mountain Lion so that I could sync my notes with my iPhone that already syncs notes with a specific email address I use for school, but during the install it automatically set up Notes to sync w the wrong email addy. It looked in Mail, which had 5 email accounts set up in it, and for some reason picked the only one that I no longer use because it is for a school that I no longer attend. How can I fix it so that it syncs with the correct email account for notes and calendar? There don't seem to be any settings available other than to check if you want to use the basic features. It also said during the set up that it was setting up 'find my mac' but if I look on the iCloud website there is nothing showing there for finding my mac.
    At this point I feel like I wasted my money paying for this supposed upgrade. I got nothing for it but frustration. It even automatically set my security settings to allow only downloads from the Mac store so the first time I went to download something I had to stop what I was doing and go correct settings first. I feel like there should be a security setting to block downloads from the Mac store so I don't accidentally end up clicking the wrong thing and being charged.

    iCloud isn't syncing them on your phone.  You simply added the email account to your phone and enabled calendar and notes syncing with the email provider, and the calendar and notes appear in the calendar and notes apps on your phone.  You can do this with Gmail, Yahoo and other IMAP account.  iCloud email is just another IMAP account, but syncs notes with Apple's iCloud server just as Gmail syncs notes and calendars with Google's server.
    iCloud didnt' set up a non-iCloud account on your Mac.  When you check Mail in System Preferences>iCloud, it only creates an iCloud email account.  You can also add other email accounts to your Mac by going to System Preferences>Mail,Contacts,Calendars and clicking on the "+" sign on the bottom of the left sidebar.  If you added these other email accounts to your Mac before you upgraded to Mountain Lion, these were simply maintained on your Mac after you upgraded.

  • How can i purchase a macbook air in Nigeria? apple has no shop in the entire country and independent dealers charge ridiculously sometimes more than double the prices of mac products without guarantee of getting it with required specifications. its sad cl

    how can i purchase a macbook air in Nigeria? apple has no shop in the entire country and independent dealers charge ridiculously sometimes more than double the prices of mac products without guarantee of getting it with required specifications. its sad cos Nigeria has a very large apple market plus phones and most recently ipads especially. its been frustrating trying to get a macbook, even have to wait for when someone will travel out of the country, then you send the person(thats if you have the money at that time). Please somebody help inform apple maybe they can do something about this, its really disappointing.

    This is a user-to-user technical support forum. You're not addressing Apple here. Use the apporpriate link on fhe Feedback page to let Apple know how you feel:
    http://www.apple.com/feedback

  • SharePoint Designer 2013 (2010 Platform Workflow) - How can I create a new list item with a SPECIFIC content type?

    In SharePoint 2010 I created workflows that used the 'Create list Item' Action, which then set the Content Type ID (so I could create documents of various types in a document library). 
    We just switched to the SharePoint 2013 platform, and now the drop down for Content Type ID is blank in all of the workflows that are still using the SharePoint 2010 platform.  Is there any way to create a list item with specific content
    type?  Even if I could just input a string into that field instead of using this blank drop-down.  Please help! 

    Hi Sarah,
    According to your description, my understanding is that you cannot create a new list item with a specific content type using SharePoint 2010 Platform Workflow.
    I tested the same scenario in my environment, and the Create List Item worked fine with the specific content type.
    How did you create the content type?
    Please check if the content type is added to the list/library the workflow associated with.
    Best regards.
    Thanks
    Victoria Xia
    TechNet Community Support

  • How to search for a message or thread with a known message ID in forum?

    How to search (or "swich") to a thread with a known ID ? The "Search
    Message" yields no results when searching for a message ID. Is there a
    other proper way for referencing a thread or message?

    If you want to keep the threads for yourself, you can use your favorites menu or the site's bookmarks option.
    If you have to transfer the number to some one else, the URL format looks fairly simple -
    http://  forums.ni.com/ni/board/message?board.id=board number\name&message.id=your number.
    if you enter the same board, you will have the board number. This doesn't look like a particularly convenient way, but I don't have a problem with copying and pasting URLs.
    The other option would be to do a search, but that is not guranteed to give you an exact answer.
    Try to take over the world!

  • How to create a String with a specific size?

    how to create a String with a specific size?
    For example I want to create different Strings with the size of 100 , 1000 or 63k byte?

    String are immutable so just initialize it with the number of characters you want.
    You might want to look at java.lang.StringBuffer and see if that's what you want.

  • How do i run two threads with different sleep times?

    How do i run two threads with different sleep times?
    Ive got thread A and thread B, they both update a jpanel.
    They both start when i press the start button.
    However thread A updates every 250ms and thread B updates every 1000ms. i cant just run them both at 250ms becuase this will mess it up.
    So for every four runs of thread A i want thread b to only be run once
    Does anyone know how to do this?
    Thanks, Ant...

    ok, ive done it but now i cant stop it!
    ive added buttons to start and stop, the start button works but the stop button doesnt. why doesnt "t.stop();" work?
        public void run() {
            while(t == Thread.currentThread()) {
                System.out.println("No " + t.getName());
                if (t.getName().equals("1")){
                    try {
                        t.sleep(1000); // in milliseconds
                    } catch (InterruptedException e) {}
                } else{
                    try {
                        t.sleep(250); // in milliseconds
                    } catch (InterruptedException e) {}
        }

  • How to handle threading for TCP communicat​ion?

    Hi,
    I've a project to control two separate applications (C++ and LabView) and both of them are implemented as server. Another client program (C++) is used to control those application. The communication among them are implemented using TCP socket. The client program sends message to start or stop some tasks on the servers. The client program also sends time (hh:mm:ss) with the start and stop message to determine when to start or stop.
    In C++ application (server): The application listens for connection and when gets  one, it creates a communication thread to handle that and again listen for another connection. The communication thread handles message passing and when it receives start or stop message, it creates a timer thread with the received time to trigger a task at specified time. And after that it waits for message from the client. So, here, when thread (communication, timer) is needed, it is created.
    In LabView (server): I've tried to create same thing as the C++ server. But, from LabView manual and others forum threads, I got that LabView is multithreading and it can be done using independent loop. So, I'd to create four loops in a diagram:
    1. Listen for new connection
    2. Handle communication for already received connection
    3. Start timer
    4. Stop timer
    and they are run at the beginning of the execution and communication among them are managed using local variables. But, 2,3 and 4th loop can handle only one connection and it can handle another if the current is closed. But, the C++ application can handle more than one connection by creating thread when it is necessary but not at the beginning of the execution of the application.
    Is there a better way to implement this in LabView?
    Is it possible to handle multiple connections and create diagram node/block (like thread) dynamically like C++?
    Thanks.
    Using LabVIEW 2010, Visual C#, Visual C++ (2005, 2008, 2010)
    Solved!
    Go to Solution.

    There are several ways to do this in modern LabVIEW and you should probably search the Example Finder for some TCP examples. The classic way is to transfer the connection refnum from the listen loop to a communication loop that adds it to an array of connection IDs and then continously iterates over this array to do the communication. It works since about LabVIEW 4.0 perfectly for me even for applications with HTTP based communication protocol. But you need to make sure of course that the communciation handling for one connection isn't delaying its work for some reasons as that would delay the handling of the other connections too, as they are really worked on sequentially. If you encounter an error, the connection ID is closed and removed from the array.
    The other is that you create a VI that does your whole communication and terminates itself on an error or when getting the quit command. Make this VI to be reentrant and then launch it through VI server as reentrant instance, passing it the newly received connection refnum form the listen loop. Then use the Run method to let it start and operate like an independant thread.
    For all of these you should be able to find an example in the Example Finder when searching for TCP.
    Rolf Kalbermatter
    CIT Engineering Netherlands
    a division of Test & Measurement Solutions

  • How to remove a dispatcher with a specific index (conf_indx)

    Hi,
    A few details:
    We are on 11.2.0.3 linux 64bit.
    We use both dedicated and shared connection.
    We have many environments (an environment consists of many schemas) in a single DB.
    For each environment we create at least one service (we know # of services is limited to ~150 in 11.2) - in example for environment with suffix LAB1 we create a service called DB_LAB1
    in example:
    exec dbms_service.create_service('DB_LAB1','DB_LAB1');
    exec dbms_service.start_service('DB_LAB1');
    For clients to be able to connect to the service_name using shared mode - we also create a dispatcher per environment - serving that specific service -
    in example:
    alter system set dispatchers='(index=30)(protocol=tcp)(service=DB_LAB1)(dispatchers=1)'
    I have a few environments which I would like to remove - including their services and dispatchers.
    removing the services is easy using dbms_service - however I did not find a way to remove/delete a dispatcher with a specific index.
    Say I have conf_indx 1..50 used and I would like to remove conf_indx=30 (the one which I created above) - how can I do that?
    Stopping the dispatcher process (Dxxx) does not remove the row from v$dispatcher_config - it only shows that the number of dispatchers for that row is 0.
    Bottom line - how to remove a specific dispatcher with a specific dispatcher-index - without affecting all the other dispatchers which I would like to preserve?
    Thanks.
    Mor

    Ok, but how does one remove some of the applications that are appear in the context menu for a given file type? Is there an asc file which can be edited?
    For example, in my system a PDF can be opened with over 10 applications. I would like to see just the three ones I use: Acrobat, Skim and Preview.
    Thanks in advance.

  • How to create a date object with a specific time?

    How can I create a date with today's date but with a specific time, say: 20:00:00?
    Thanks in advance.

    Don't forget about those pesky milliseconds!I'd have gotten away with it too.. if it hadn't been
    for that pesky BigDaddyLoveHandles.I'm in top form today. On the drive in to work I managed to
    push two scooter riders off the road and gave the finger to
    a Prius owner.

  • In CQ 5.4 how to read search trends(keywords) with in specific date (like last week, 30 days...)?

    I have a requirement to display popular search key words with in specific date range. Like search key words searched in last week/ in last 30days/in 90 days.
    how to get date range searched keywords from Search Trends?? is there any other way to get these??

    Issue was due to a syntax error. Case closed.
    Thanks!
    -OS

Maybe you are looking for

  • How can I prevent my iPhone4 from opening the 'next' e-mail when I delete an e-mail?

    Subject says it all. When viewing an e-mail, I delete it. Rather than just going back to the list of e-mails, my iPhone opens up another unread e-mail (seems to sometimes open a newer one, and sometimes an older one). I don't want it to do that.

  • Generate html report

    I need to add text to my html report as my VI is running (or after all VI's are finished running). I have different sub-VI, and my html report has to include the result for all of the test. How do I code LabView to append text as each test is finishe

  • I PHOTO NOT OPENING FULLY

    Had a software problem and took my powerbook to apple store where it was completely wiped clean and reinstalled all software ..... now when i open i photo the pictures wont open fully and remain unclear as if they are were taken with a 1 million pixe

  • Itunes doesn't see all my iphoto photos

    I noticed that I checked "sync all photos, events, and albums" in my preferences in iTunes (10, Snow Leopard) but not all photos sync to my iPad.  It's driving me crazy!

  • HP Lists 3 Options For Scanning

    The following link (shown multiple times in this forum) lists 3 options for implementing the scanning feature of HP Photosmart scanners with OS X 10.6: http://h10025.www1.hp.com/ewfrf/wc/document?docname=c01846935&cc=us&dlc=en&lc=en &jumpid=regR1002U