Stopping thread with timeout using threadpool

Is there any way to set thread timeout within Executor.newFixedThreadPool ? I have a long queue around 5M which is creating with:
ExecutorService executor = Executors.newFixedThreadPool(500);
total = 10000;
while (totalRows > 0) {
                localStatement.executeQuery("SELECT domainID, domain FROM com WHERE status = '' LIMIT " + total);
                totalRows -= total;
                localResultSet = localStatement.getResultSet();
                while (localResultSet.next()) {
                    HttpGet httpget = new HttpGet("http://" + localResultSet.getString("domain").toLowerCase());
                    executor.submit(new GetThread(httpClient, httpget, localResultSet.getInt("domainID")));
                Thread.sleep(1000);
                while (((ThreadPoolExecutor) executor).getActiveCount() > 10) {
                    try {
                        Thread.sleep(1000);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                localResultSet.close();
                System.out.println("New cycle");
            }But sometimes threads lock and cycle can't finish. Is there anyway to stop thread after N seconds? I can encapsulate Runnable into another Runnable and stop it from there, but it doubles threads, and I believe its not a good way.

yes, you need at least one more thread. you could use one thread to monitor multiple other threads, but you need at least one more thread to wake up after the timeout and check on/cancel the main task.

Similar Messages

  • Cannot Stop Thread with ServerSocket

    Hi
    I have a problem with a Thread that runs a ServerSocket. I want to stop this Thread from the main-application:
    Thread class:
    Constructor:
    serverSocket = new ServerSocket(address, port);
    public void run() {...
    while (true) { ....
    clientSocket = serverSocket.accept();
    I want to do the following in the main-application:
    because I want to set up a Thread with a new ServerSocket:
    myThread = null; // to stop the Thread, I also have tried to interrupt without success
    myThread = new Thread(); // => BindException and serverSocket == null;
    I always catch a BindException and in the Thread-Constructor the serverSocket is set null !
    How can I avoid this?
    I need to get a new serverSocket!!
    Can anyone help me?
    thanks, walter

    Thank's for reply: The problem I have is the following: My domain has a dynamic IP, so after the IP changes the s.accept() does not work any more!
    try // Point 1 *)
    ServerSocket s = new ServerSocket(portNumber);
    for(;;)     
    Socket incoming = s.accept(); // does not work after IP changes
    new ThreadedEchoHandler(incoming, i).start();
    So I have to detect that the IP has changed and have to start again at Point 1
    How can I do this?
    thx walter

  • Stop thread with error 1000

    Iam trying to start a thread by dynamically calling a re-entry vi and get a calling reference therefore. When I need to close the vi, I just use that vi reference to close it.
    But I got the Error 1000 LabVIEW:  The VI is not in a state compatible with this operation.
    Please see the attached piece code for the way I am open and close it(, since the original code is a bit complex)
    P.S.
    What is the best way to stop one of the multi dynamically called out re-entry vi outside itself somewhere else.
    Also if multi instances of one re-entry vi are called out, how to monitor their existing status in debugging, such as whether they been killed. The log file some time is a bit slow.
    Thanks
    Solved!
    Go to Solution.
    Attachments:
    Open Close.vi ‏19 KB
    PubSub_QueueServiceTask.vi ‏22 KB
    PubSub_TCPServiceTask.vi ‏15 KB

    Hi,
    Even though the subVI that you called is running, it is not running under its own execution; it is part of the execution of the top-level VI. The execution of a VI depends on the execution of the subVI that is called, so you are not allowed to abort the execution of a subVI. Even though two parts of the main VI may be running in parallel (the subVI and the VI Server Abort command), the subVI is not executing on it's own; it is part of the caller VI.
    In order to abort a subVI from another VI, it needs to be running as a VI, not as a subVI. To make this happen, you would need to start the subVI through VI Server, using an Invoke node with the Run method. You also need to set the Wait until done option to False to eliminate the data dependencies of this VI. This way you can run and abort a VI from another VI. The major drawback to this however, is the greater difficulty of passing data values to the called VI. You would have to use the Set Control Value and Get Control Value methods to pass data to and from the called VI. I attached the examples below.
    Sincerely,
    Gunyapart Deephanphongs
    Application Engineer
    NI ASEAN
    Message Edited by Chongnang on 11-21-2008 03:22 AM
    Attachments:
    That.vi ‏11 KB
    This.vi ‏12 KB

  • Troubles with timeout using java.nio.channels and non-blocking sockets

    Hello.
    I have a server application that employs java.nio.channels with non-blocking sockets.
    The server waits for connections. The client should connect and be first in sending data.
    Timeouts are significant! If client exceeds the allowed time to send data, the server should break the connection.
    The huge trouble I've discovered that I cannot control the timeout when client connects but remains silent.
    My code looks as follows:
    <pre>
    Selector oSel;
    SocketChannel oSockChan;
    Socket oSock;
    SelectionKey oSelKey;
    Iterator<SelectionKey> oItSelKeys;
    int iCurrState, iMask, iCount;
    iCurrState = INT_SERVER_WORKING;
    iMask = SelectionKey.OP_ACCEPT | SelectionKey.OP_CONNECT | SelectionKey.OP_READ | SelectionKey.OP_WRITE;
    while ( iCurrState == INT_SERVER_WORKING )
    try
    *// retrieving next action*
    iCount = oSel.select();
    if ( iCount > 0 )
    oItSelKeys = oSel.selectedKeys().iterator();
    while ( oItSelKeys.hasNext() )
    oSelKey = oItSelKeys.next();
    oItSelKeys.remove();
    if ( oSelKey.isValid() )
    switch ( oSelKey.readyOps() & iMask ) {
    case SelectionKey.OP_ACCEPT :
    oSockChan = oSSockChan.accept();
    oSockChan.configureBlocking(false);
    oSock = oSockChan.socket();
    oSock.setKeepAlive(true);
    oSockChan.register(oSel,SelectionKey.OP_READ,new MyPacket(oSock.getInetAddress(),oSock.getPort()));
    break;
    case SelectionKey.OP_READ :
    oSelKey.interestOps(0);
    ((MyPacket) oSelKey.attachment()).inRequest(); *// preparing request*
    this.getReader().add(oSelKey); *// sending key to reading thread*
    break;
    case SelectionKey.OP_WRITE :
    oSelKey.interestOps(0);
    ((MyRequest) oSelKey.attachment()).inResponse(); *// preparing response*
    this.getWriter().add(oSelKey); *// sending key to writing thread*
    break;
    case SelectionKey.OP_CONNECT :
    default :
    *// nothing to do*
    catch ( IOException oExcept )
    *// do some actions*
    </pre>
    Timeouts are easily controlled by reading and writing threads (see OP_READ and OP_WRITE ).
    But when a client just connects without consequent data send, the state of this connection remains as OP_ACCEPT. The connection remains open for arbitrarily large time and I cannot control it!
    Please help with idea how can I terminate such connections!

    How can I process the keys that weren't selected at the bottom of the loop? Should I use the method keys() ?Yes. Form a new set from keys() and removeAll(selectedKeys()). Do that before you process selectedKeys().
    And the second moment: as I understood a single key may contain several operations simultaneously? Thus I should use several if's (but not if/else 'cause it's the equivalent of switch ... case ).If there is anything unclear about 'your switch statement is invalid. You need an if/else chain' I fail to see what it is. Try reading it again. And if several ifs were really the equivalent of "switch ... case", there wouldn't be a problem in the first place. They're not, and there is.

  • I have several times tried to stop following a thread in the PDF's forum about security issues and i still keep getting flooded with emails from this thread. I used the action within the thread that says stop following but appears to have no effect I stil

    I have several times tried to stop following a thread in the PDF's forum about security issues and i still keep getting flooded with  emails from this thread. I used the action within the thread that says stop following but appears to have no effect I still keep  getting from 5 to 20 emails daily. Please help!!!!!!!

    This may be helpful: How do I disable email notifications?

  • Use of Threads with JSP's

    Can you use threads in a web application that uses JSP's plus Servlets and Beans ?
    We have a JRUN 3.1 application using JSPs, Servlets and Beans. Shortly after we went live it became apparent that any 2 users using the same object experienced problems as one object was overwriting another. In a panic the problem was solved by whacking SYNCHRONISED on all objects.
    Now we want to write another application, are there strategies for using Threads with JSPs?
    Would this be part of the webserver configuration or would the application be coded in a certain way ?
    Please can you give me a simplistic answer or point me to some documentation that gives a simple overview.
    Thanks Steve

    Hi,
    You can use thread with jsp, i am sending u a example
    package thread;
    import java.io.Serializable;
    public class TaskBean implements Runnable, Serializable {
    private int counter;
    private int sum;
    private boolean started;
    private boolean running;
    private int sleep;
    public TaskBean() {
    counter = 0;
    sum = 0;
    started = false;
    running = false;
    sleep = 100;
    protected void work() {
    try {
    Thread.sleep(sleep);
    counter++;
    sum += counter;
    } catch (InterruptedException e) {
    setRunning(false);
    public synchronized int getPercent() {
    return counter;
    public synchronized boolean isStarted() {
    return started;
    public synchronized boolean isCompleted() {
    return counter == 100;
    public synchronized boolean isRunning() {
    return running;
    public synchronized void setRunning(boolean running) {
    this.running = running;
    if (running)
    started = true;
    public synchronized Object getResult() {
    if (isCompleted())
    return new Integer(sum);
    else
    return null;
    public void run() {
    try {
    setRunning(true);
    while (isRunning() && !isCompleted())
    work();
    } finally {
    setRunning(false);
    And JSP page start.jsp
    <% session.removeAttribute("task"); %>
    <jsp:useBean id="task" scope="session"
    class="thread.TaskBean"/>
    <% task.setRunning(true); %>
    <% new Thread(task).start(); %>
    <jsp:forward page="status.jsp"/>
    ///////////////// status .jsp
    <jsp:useBean id="task" scope="session"
    class="thread.TaskBean"/>
    <HTML>
    <HEAD>
    <TITLE>JSP Progress Bar</TITLE>
    <% if (task.isRunning()) { %>
    <SCRIPT LANGUAGE="JavaScript">
    setTimeout("location='status.jsp'", 1000);
    </SCRIPT>
    <% } %>
    </HEAD>
    <BODY>
    <H1 ALIGN="CENTER">JSP Progress Bar</H1>
    <H2 ALIGN="CENTER">
    Result: <%= task.getResult() %><BR>
    <% int percent = task.getPercent(); %>
    <%= percent %>%
    </H2>
    <TABLE WIDTH="60%" ALIGN="CENTER"
    BORDER=1 CELLPADDING=0 CELLSPACING=2>
    <TR>
    <% for (int i = 10; i <= percent; i += 10) { %>
    <TD WIDTH="10%" BGCOLOR="#000080"> </TD>
    <% } %>
    <% for (int i = 100; i > percent; i -= 10) { %>
    <TD WIDTH="10%"> </TD>
    <% } %>
    </TR>
    </TABLE>
    <TABLE WIDTH="100%" BORDER=0 CELLPADDING=0 CELLSPACING=0>
    <TR>
    <TD ALIGN="CENTER">
    <% if (task.isRunning()) { %>
    Running
    <% } else { %>
    <% if (task.isCompleted()) { %>
    Completed
    <% } else if (!task.isStarted()) { %>
    Not Started
    <% } else { %>
    Stopped
    <% } %>
    <% } %>
    </TD>
    </TR>
    <TR>
    <TD ALIGN="CENTER">
    <BR>
    <% if (task.isRunning()) { %>
    <FORM METHOD="GET" ACTION="stop.jsp">
    <INPUT TYPE="SUBMIT" VALUE="Stop">
    </FORM>
    <% } else { %>
    <FORM METHOD="GET" ACTION="start.jsp">
    <INPUT TYPE="SUBMIT" VALUE="Start">
    </FORM>
    <% } %>
    </TD>
    </TR>
    </TABLE>
    </BODY>
    </HTML>
    ////////////////////////////// stop.jsp
    <jsp:useBean id="task" scope="session"
    class="thread.TaskBean"/>
    <% task.setRunning(false); %>
    <jsp:forward page="status.jsp"/>
    deploy it into ur server and run start.jsp
    and see whatb happens

  • Interpretation of the use of threads with Sessions in the JMS Specification

    Hello,
    I’ve been interacting with two JMS Providers which do a different interpretation of the JMS Specification with the use of different threads for accessing to a session and session’s related objects.
    The question is:
    When a client is consuming messages asynchronously, is it possible to access session’s related objects from a thread different to the one dedicated to the asynchronous consumption, on (thread of control)?
    -     Never?
    -     Yes, but the client should provide explicit synchronization.?
    Our execution scenario is:
    1.- Messages are consumed asynchronously from a dedicated thread.
    2.- From other thread, messages consumed are acknowledged.
    In the JMS specification there is, at least, two parts where this issue is treated:
    1.- The first one (4.4.1 - page 60):
    +“There are no restrictions on the number of threads that can use a Session object or those it creates. The restriction is that the resources of a Session should not be used concurrently by multiple threads. It is up to the user to insure that this concurrency restriction is met. The simplest way to do this is to use one thread. In the case of asynchronous delivery, use one thread for setup in stopped mode and then start asynchronous delivery. In more complex cases the user must provide explicit synchronization.”+
    This extract, makes me think that it is possible the access from different threads, but If I do that, I should provide explicit synchronization.
    2.- The second one (4.4.6 – page 62,63)
    +"Once a connection has been started, any session with a registered message listener(s) is dedicated to the thread of control that delivers messages to it. It is erroneous for client code to use this session or any of its constituent objects from another thread of control. The only exception to this is the use of the session or connection close method"?+
    This extract, could be interpreted as that the concurrent access is never allowed in the described situation.

    I think the key words are in 4.4.6 (and also the javadoc for Session): "Once a connection has been started, any session with a registered message listener(s) is dedicated to the thread of control that delivers messages to it".
    My interpretation of this is that you when you register a message listener and call connection.start(), the thread which delivers messages to the listener should be thought of as "using the resources of the session" (as mentioned in 4.4.1) continuously until the connection is stopped (or until the session or connection is closed). it doesn't matter whether the session is executing onMessage() or not.
    Given this, both 4.4.1 and 4.4.6 say the same thing: that once you have registered and started a message listener, the only thing you can do to the session from another thread is to close it.
    I agree the spec could be clearer. In particular the words "In more complex cases the user must provide explicit synchronization" in 4.4.6 should be clarified to state what this actually means rather than give a hint.
    Please note that work has just started on updating the JMS specification, so now is a great time to report areas of the JMS spec which would benefit from clarification. If you'd like this to be considered for clarification, please report it in the official JSR 343 issue tracker at http://jms-spec.java.net
    Nigel

  • HT203175 While trying to use my iTunes library it will suddenly stop working with the erro message Runtime error R6025 pure virtual function call.  HELP!!!

    While trying to use my iTunes library it will suddenly stop working with the error message Runtime error R6025 pure virtual function call.
    Help???

    Just responded to this in another thread (note we used Captivate 7 so it might be a different error).
    We found that when we created files with embedded swf files that existed ABOVE widgets in the timeline, when someone else tried to open our file it broke/we got the runtime error. The original person could still open it for a time, but eventually the cache would clear and they couldn't.
    However, if we ensured swf files are BELOW widgets in the source files, it didn't break. In fact, if we found one that was breaking and got the author to move the swf file on the timeline, it would start working for others.
    STRANGE! Let me know if this works for you to!

  • I am trying to use a Logitech USB headset to record with screencast o matic. In the sound file of system preferences the headset is recording audio. However it stops working when I use screen cast o matic. Any advice?

    I am trying to use a Logitech USB headset to record with screencast o matic. In the sound file of system preferences the headset is recording audio. However it stops working when I use screen cast o matic. Any advice?

    See these threads for some possible solutions:
    Bluetooth and 10.7
    Bluetooth speaker error

  • I recently started to get an error message "MobileMe Services" have stopped working.  I use Vista.  If I remove the MobileMe program, will it affect syncing with my iPhone or with Google Calendar?

    I recently started to get an error message "MobileMe Services have stopped working".  I use Vista.  If I remove the MobileMe program, will it affect syncing with my iPhone or with Google Calendar?

    No, just uninstall the MobileMe control panel. All Mobileme services have been discontinued, so the control panel is not doing you any good being in there at present.

  • After I upgraded my Mac with Yosemite, Photoshop Elements 12 stops responding when you use editing tools like eraser, clone stamp.

    After I upgraded my Mac with Yosemite, Photoshop Elements 12 Editor stops responding when you use some tools like eraser, clone stamp.

    This should help. Photoshop Elements doesn't respond when you use editing tools in Mac OS X 10.10
    ~ Arpit

  • I am having trouble with my JAVA Applet. It isn't functioning on SAFARI.    It seems to have stopped working and I used it on SAFARI last year. Any suggestions ?

    I am having trouble with my JAVA Applet. It isn't functioning on SAFARI.    It seems to have stopped working and I used it on SAFARI last year. Any suggestions?

    Post in the Safari forum area.

  • Why has my ipad mini stopped connecting with my iPhone 4S? I used to use it to download books, or transfer emails to my ipad mini. It was fine 3 days ago, now I get a message saying " cannot join with iPhone" Any help greatly appreciated.

    Why has my ipad mini stopped connecting with my iPhone 4S? I used to use it to download books, or transfer emails to my ipad mini. It was fine 3 days ago, now I get a message saying " cannot join with iPhone" Any help greatly appreciated.

    You can try resetting your iPad and iPhone by simultaneously pressing and holding the Home and Sleep/Wake buttons until you see the Apple Logo. This can take up to 15 seconds so be patient and don't release the buttons until the logo appears.
    Try again to see if the problem persists.

  • My iphone 5c has stopped synching with my pc using calender thru microsoft outlook, any ideas on how I can get my iphone to synch with my calender on my pc in outlook again

    my iphone 5c has stopped synching with my pc using calender thru microsoft outlook, any ideas on how I can get my iphone to synch with my calender on my pc in outlook again

    Hello leighfromgold coast,
    Thanks for using Apple Support Communities.
    If you're having issues with syncing your Outlook calendar with your iPhone, then please follow the troubleshooting in the article below.
    Troubleshooting Sync Services on Windows with Microsoft Outlook 2003, Outlook 2007, or Outlook 2010
    Cheers,
    Alex H.

  • My track pad stopped working with a single finger/double click when I try to open emails, and when I try to open apps on desk top.  If I use two fingers, and then click open, I can open them.  Thank You for your help.

    My track pad stopped working with a single finger/double click when I try to open emails, and when I try to open apps on desk top.  If I use two fingers, and then click open, I can open them.  Thank You for your help.

    Greetings ascnephew8,
    It seems your trackpad isn't working as you expect it to. Have you reviewed the trackpad settings in System Preferences? The following article provides trackpad setting details which may help:
    OS X Mountain Lion: Change the way your trackpad works
    Thank you for contributing to Apple Support Communities.
    Best,
    Bobby_D

Maybe you are looking for