How to stop a threads that makes I/O calls ?

Hi,
I've a business method that calls a Stored Procedure and makes lots of calculations. This method works inside its own thread, because I do not want to stop the GUI from accepting user actions.
My problem is : this method may take from 5 minutes to 1 hour to process, depending on the size of the input. Sometimes, for any reason at all, the user may want to stop this execution (pressing a button on the GUI). How can I safely stop the thread ?
I know I should not use stop() and suspend() because they are deprecated. And I do not use loops (remember it calls only a StoredProcedure that makes all processing), so I cannot use a variable nor interrupt(), because they do not work.
Do you know any other way to stop this thread's execution ? By the way destroy() is not implemented.
Thanks and regards.
Bruno

Are you saying that the 5 minutes to an hour is all spent in the stored procedure?
If so the only real solution is to kill the statement - I'm not sure how the DB will handle that, but it will certainly free up your cycles.
To do that without violating encapsulation, you just need to keep a reference to an object that knows something about the DB connection - you don't have to actually pass around the JDBC objects.
Consider an object like this:
public class DoLongProcedure {
   private Statement dbStatement;
   public double doLongCalculation() {
      dbStatement.execute(...);
      // etc
   public void interruptCalculation() {
      dbStatement.close();
}You create an instance of this object and call its doLongCalculation() method to start everything. You have a reference to this object somewhere, because you are waiting for a response. When the user wants to cancel the process you just call the interruptCalculation() method.
You have not violated your separation of functionality - if you find a new way to stop the process without killing the statement later, you just reimplement that method.

Similar Messages

  • How could stop this thread that calls an externall function ?

    Hi all.
    i need an help about syncronization of two thread.
    the first one is smt like that
    Thread t = new Thread(new Runnable() {
                   public void run() {
                        long startTime = System.currentTimeMillis();
                        while (System.currentTimeMillis() - startTime < lifetime) {
                             if (c.dynamic) {                    
                                  c.adjustLayout();
                             c.repaint();
                             try {
                                  Thread.sleep(delayMillis);
                             catch (InterruptedException ex) {
                                  // ignore
              t.start();where c.adjustLayout(); & c.repaint(); are syncronized over a astructure called G using syncronized(G)
    now the second thread is:
         Thread t = new Thread(new Runnable() {
                   public void run() {
                        long startTime = System.currentTimeMillis();
                        while (System.currentTimeMillis() - startTime < lifetime) {
                             if (c.updateVisible) {
                                  c.updateVisibleGraph();
                             try {
                                  Thread.sleep(delayMillis);
                                  Thread.yield();
                             catch (InterruptedException ex) {
                                  // ignore
              });where the function c.updateVisibleGraph(); is syncronized over G as well. the problem is that this function, takes seconds, and block thread A and B (both of them ar suyncronized, so if B is running A cannot run).
    how can i stop c.updateVisibleGraph(); in the middle of the exectuion or each 50ms.
    is this possible?
    thanks
    Edited by: ELStefen on 26-ago-2010 16.08
    Edited by: ELStefen on 26-ago-2010 16.11

    isocdev_mb wrote:
    Using a synchronized-block is not designed to give up the lock for little while, it holds the lock until the block ends. Your requirement needs a far more fine-grained approach, quite different from your sketched implementation.
    It would involve quite an amount of guessing of what's behind the G and c your mentioning to suggest a way out. Please elaborate on what you're trying to achieve so that we can suggest how to do that...
    P.S. this forum likes problems to come with a simple working example, which you did not provide and a description of what you'd like to achieve, some context.as i thought, damn.
    Well give a working example is quite complex for the time being. Is a big project and take out this part is quite complex. But i can explain the goal.
    Practically there's a Graph (G)
    this graph is used by 2 thread, one is the update the edges and vertices, adding and removing them. the other one thread is the painter of the graph.
    the problem is when the first thread is updating the structure of G, sometimes this operation takes time (seconds) and being synchronized on G it blocks the paint thread as well.
    the thing that i would like to have is keep the painting working each tot millisecond. the updating thread works when necessary. if the update operation takes to long, it has to be stopped in the middle (and it has to restart after the paint) in a way that the paint thread can be executed.
    as the code is, and as you said, synchronizing the entire block code cannot works as i want.
    is this more clear? any clue about how can i solve this?
    many thanks
    Edited by: ELStefen on 27-ago-2010 12.43

  • How to stop the thread?

    Hi,
    How to stop the thread in java. This is my program.
    import java.net.InetAddress;
    public class ThreadPing extends Thread {
         ThreadPing(String pingIP)
              super(pingIP);
              start();
         public void run()
              try
              String pingIP = Thread.currentThread().getName();
              InetAddress inet = InetAddress.getByName(pingIP);
              Boolean get=inet.isReachable(1500);          
              if(get==true)
                   System.out.println(inet.getHostName());               
              }catch(Exception e)
         public static void main(String args[])
              for(int i=1;i<=100;i++)
                   String pingIP = "192.168.1."+i;
                   ThreadPing tp = new ThreadPing(pingIP);
    Thanks in advance.

    The simplest way to stop all the thread is to make all thread daemons and exit the program when you want them to stop.

  • How to stop main thread ?

    Hi,
    Inside my java class, after I launch a GUI, I want to stop this main thread. After user make some choice and close GUI window, then, I want to go back to main thread. I use wait() method inside my class to stop main thread , but it does not work and it give me "IllegalMonitorStateException" error. I met same thing, when user close the GUI window and call method notifyAll(). How to stop main thread for a while and how to go back?? Thanks
    Gary

    Hi,
    you can create a boolean, and create a while loop, with a Thread.sleep(time); when you want to continue, you just have to change the state of your boolean. So you don't hava to exit the main. And you can't restart a run() in a thread. You can run it only once, so try to keep in your run() with an appropriate loop.
    Hope it helps.
    S�bastien

  • How to stop a process (that is executing)

    Hi all
    my question is How to stop a process that is executing ?
    some other languages has a function called yield() in java how I can do it.
    thanks

    You can tell a Thread to yield - That is, cause the currently executing thread object to temporarily pause and allow other threads to execute.

  • How to stop a thread without the deprecated Thread.stop() method?

    Hi,
    I am writting a server application that launches threads, but the run() implementation of these threads are not written by me (i.e. i have no control over them): they are third-party programs. That's why i could not use the well known Java tutorial way to stop a thread (i.e. with a global variable that indicates the thread state).
    I would like my server to be able to stop these threads at any time, but without using the deprecated Thread.stop() method.
    Any ideas ?
    Thanks in advance,
    Fabien

    Thanks Pandava!
    I was arrived at the same conclusion... As to me, it is a very bad issue, because it means for example that a servlet server can not stop any servlet it launches (especially for preventing infinite loops).
    If i want to be strictly JDK 1.4 compliant, i should not use Thread.stop(). But if i don't use it, i don't have any ideas of how stop a thread that i don't control...

  • I need to know how to stop a notification that keeps coming up when playing a spades game, that keeps telling me to go to the game center. I even shut off the notifications in the settings, this is an anoying problem

    I need to know how to stop a notification that keeps coming up when playing a spades game, that keeps telling me to go to the game center. I even shut off the notifications in the settings, this is an anoying problem

    I'm pretty sure this is an Apple thing and you can't do anything about it. To get rid of the notification just do as it asks then try to forget about it.

  • How to stop a thread at the end of another

    hello
    I want to run two threads. They start at the same time, and I want one of them to end when the first one finishes.
    I have a main class, a GUI. When I click on a button, it processes an action( first thread), and since this action takes some time, I decided to create a second thread that is a GUI that is a dialog box that says that it is being processed...
    So my dialog bow has to disappear when the process ends.
    I've already tried this:
    boolean stop = false;
    Connect connect = new Connect(this);
    connect.start();
    LdapSearch searching = new LdapSearch();
    searching.start();
    while( connect.isAlive() ){
         if( !connect.isAlive() ){
              stop = true;
    if( stop == true ){
                           searching.interrupt();
    }but unfortunately the text written on my dialog box disappears....
    does anyone knows how I can make a thread stop at the end of another properly?
    thanks for your help!!
    Philippe

    sorry the code i tried is:
    boolean stop = false;
    Connect connect = new Connect(this);
    connect.start();
    LdapSearch searching = new LdapSearch();
    searching.start();
    while( stop == false ){
         if( !connect.isAlive() ){
              stop = true;
    if( stop == true ){
         searching.interrupt();
    }

  • How to stop a thread in java 5 for a real-time system??

    Hi,
    In Java 5, thread.stop is deprecated. We need to modify some variable to indicate that the target thread should stop running. "The target thread should check this variable regularly........"
    We are currently developing a simple real-time operating system using the basic features of java. It is running on top of SunSPOT (JAVA5). My question is I need to stop a thread in a scheduler loop of a real-time operating system. We cannot check it regularly. Otherwise it is not a real-time operating system.Is there anyway else to do this?
    Thanks,
    Qing

    That's rather hard to answer. You say you are writing in Java, but you're writing an OS. BUt what's executing the Java - you need a VM of some form. Is that a real-time or non-real-time VM? How it does things ultimately controls how effectively you can do what you are trying to do.
    The simple answer is that Thread.stop() is deprecated and that it will not stop a thread in all situations anyway - eg trying to acquire a monitor lock. But all Thread.stop does is make an exception pending on the thread, and as the thread executes it polls to see if there is an exception pending. When this happens depends on the VM: it might be after every bytecode; it might be when the thread transitions states (eg thread-in-java, thread-in-vm, thread-in-native) - it all depends. But it is polling - just the same as checking that variable - it's just implicit in the VM rather than explicitly in your code.**
    The RTSJ adds a new form of asynchronous termination requests through the AsynchronouslyInterruptedException (AIE). But it only affects code that explicitly declares that it expects AIE to occur, and there are also deferred sections where the AIE will remain pending. Writing code that can handle AIE is very difficult because the normal Java rules are "bent" and finally blocks do not get executed inside AIE-enabled code.
    So as I said this is very hard to answer, it really depends what exactly you are running on and what you are trying to achieve.
    ** Note: some people used bytecode rewriting tools to add this kind of polling as a post-processing step. Perhaps that is something you might be able to do too.
    David Holmes

  • New Socket takes too long / how to stop a Thread ?

    Hello to everyone,
    I have a problem that I have been hunting this ol' Sun website all day for a suitable answer, and have found people who have asked this same question and not gotten answers. Finally, with but a shred of hope left, I post...
    My really short version:
    A call to the Socket(InetAddress,int) constructor can take a very long time before it times out. How to limit the wait?
    My really detailed version:
    I have a GUI for which the user enters comm parameters, then the program does some I/O while the user waits (but there is a Cancel button for the Impatient), then the results are displayed. Here is quick pseudocode (which, by the way, worked great before there were Sockets in this program -- only serial ports):
    Main (GUI) thread:
         --> reset the stop request flag
         --> calls workerThread.start(), then brings up a Cancel dialog with a Cancel button (thus going to sleep)
         --> (awake by dialog closing -- dialog may have been closed by workerThread or by user)
         --> set stop request flag that worker thread checks (in case he's still alive)
         --> call workerThread.interrupt() (in case he's alive but asleep for some reason (???))
         --> call workerThread.join() to wait for worker thread to be dead (nothing to wait for if he's dead already)
         --> display worker thread's result data or "Cancelled..." information, whichever worker thread has set
    Worker thread:
         --> yield (to give main thread a chance to get the Cancel Dialog showing)
         --> do job, checking (every few code lines) that stop request flag is not set
         --> if stop request, stop and set cancelled flag for Main thread to handle
         --> if finish with no stop request, set result data for Main thread to handle
         --> take down Cancel Dialog (does nothing if not still up, takes down and wakes main thread if still up)
    THE PROBLEM: Worker thread's job involves doing IO, and it may need to instantiate a new Socket. If it is attempting to instantiate Socket with bad arguments, it can get stuck... The port int is hardcoded by the program, but the IPAddress must be typed by user.
    If the arguments to Socket(InetAddress, int) constructor contain a valid-but-not-in-use IP address, the worker thread will get stuck in the Socket constructor for a LONG time (I observed 1m:38s). There is nothing the Main thread can do to stop this wait?
    EVEN WORSE: If the user clicks the Cancel Button during this time, the dialog goes away soon/immediately, but then the GUI appears to be hanging (single-threaded look) until the long wait is over (after which the "Cancelled..." info is displayed).
    MY QUESTION: Is there nothing the Main thread can do to stop this wait?
    Your answers will be sincerely appreciated. Despite my hopeless attitude (see above), the folks at this forum really have yet to let me down ...
    /Mel

    http://developer.java.sun.com/developer/technicalArticles/Networking/timeouts/

  • How to stop all threads running in a application

    I need to stop all the threads that are currently running in my application. How to do this.

    call System.exit();

  • How to stop a thread in java 1.5 on windows

    Hi All,
    I am using Java 1.5 on windows plateform. I want to stop all the threads which belongs to a particular process when the timeout occurs. In java 1.5 stop() method is depricated and interrupt method just sets the flag and does not stop the thread actually.
    Is there any way to destroy the thread permenently. I am using TheadPool Executor class.
    Regards
    Rinku Garg

    Hi,
    I am having a timer task which is scheduled to run after some fixed time interval when the process started.
    Now this timer task when started, should destroy the active threads of the request. When the request is timed out then the thread is action should termininate.
    In my case run method of particular thread had already made a call to Database through DAO when the time out occurs. So how can I set up a loop in run method which I found on google.
    thread.stop() is deprecated.
    thread.destroy() is deprecated.
    I used thread.interrupt() but it does not stops the thread.
    Please help me in this scenario.
    Regards
    Rinku Garg

  • How to stop a thread forcefully. do reply urgent

    i would like to stop the thread . i have used stop() method and also i have tested by giving the threadname = null. but these two not worked . how to stop thread forcefully. urgent.
    with regards

    There is no direct way to stop the thread forcefully. If you have implemented the thread, modify the code so as to break on some flag.
    i.e.
    public void run()
    while (keepRunning)
    ...do some stuff here
    and provide some way to set the boolean keepRunning as false. The loop will exit and the thread will also be destroyed.

  • How to stop a page that is partially downloaded?

    Often I want to stop a page in mid-downloaded and keep it for a while. I don't want to kill it. In Firefox 5 I can't see how to do this.

    Firefox 4.0 / 5.0 have a combined Reload, Stop, & Go button that appears at the right end of the location bar. Only one function is ever active at any one time, so combining them save UI space was a good idea. '''When a page is loading, it is a "Stop" button''', when it finished loading, it turns into a "Reload" button, and when you start to type something into the Location bar it turns into a "Go" button.
    To restore the Firefox 3 appearance you can use these steps:
    * Open the "View > Toolbars > '''Customize'''" window or right-click a vacant area on a Toolbar, ''except fot the Bookmarks Toolbar''.
    * Then drag'n'drop the Reload and Stop buttons to their previous position at the left side of the Location bar.
    # Set the order to "Reload - Stop" to get a combined "Reload/Stop" button.
    # Or "Reload - Stop" then put a flexible space in between the two to prevent the buttons from combining.
    # Set the order to "Stop - Reload" to separate them and get two distinct buttons.

  • How to stop a app that is not responding. It is always loading

    How to stop and delete an app that is no longer responding. It is always loading

    If it's a large app and you've got a relatively slow connection that it might take a while to finish loading.
    Does tapping the icon change it's 'state' ? You could try a reset and see if it resumes loading after the iPad has restarted : press and hold both the sleep and home buttons for about 10 to 15 seconds (ignore the red slider), after which the Apple logo should appear - you won't lose any content, it's the iPad equivalent of a reboot.
    Or you could try downloading it on your computer's iTunes and then sync or drag/drop it across to the iPad device.

Maybe you are looking for

  • Iphone calendar issue

    When creating an event in the calendar that spans a few days, the final day of the event does not appear in the calendar. For example: an event that you set from the 1st of April to the 5th of April, the calendar only shows the 1st to the 4th marked

  • Epson NX420 wireless printing not working

    After upgrading to Yosemite, I noticed the printing capability on my NX420 was gone. I get communication errors and a prompt to download software; but after downing, a notice for error downloading. No updates show up via App store. I have downloaded

  • Read Internal Table based on Multiple Values for Key Field

    Hi Gurus, i have one query can you tell me how read an internal table it_kna1 for multiple values of land1 DE US IND etc. i had tried as below but i could not can you try and let me knwo at the earliest. here i want read the values with DE or US and

  • How to make Bank Note style artwork.

    I am wanting to know if there is an effect or action that someone knows about that will transform a regular image into a threshold style image like found on most bank notes. With lines and dots to create the shading and gradient effects. Not looking

  • Folder contents missing in upload + 2 other issues

    I am able to upload contents through Adobe Drive's CMIS connection (5.0.1) from Adobe Bridge (CC) to Alfresco (latest public build as of this thread's start date). But, those uploads only operate in a very strict set of parameters that are not able t