Stopping  a child thread

Here is a class that will create a process thread. The process thread will talk to a database through another class.The process thread should return the result within *30* seconds.If it returns before *30* second it is fine. Help me how to stop the process if it takes more than 30 second.
public class Details{
//Method will return a Map
public Map getDetail(String name){
ProcessThread process = new ProcessThread (); //This is new thread
process.setName(name);
Thread t = new Thread(process);
long initTime = 0;
long startTime = System.currentTimeMillis();
long sleepTime = 30000;
t.start();
try{
//the process thread should return a Map with in 30 seconds.The current thread sleep for 0ne second and checks the time is exceeding *30* seconds and the process thread is still running.If the process thread returns before *30* second it is fine otherwise it shoild kill the process thread
while (t.isAlive() && initTime < sleepTime) {
initTime = System.currentTimeMillis() - startTime;     
Thread.sleep(1000);
if (elapsedTime >= sleepTime) {
throw new Exception();
}catch(Exception e){
return process.getDetailsMap();
Here a code for a process thread
public class ProcessThread implements Runnable {
private String name;
private Map detailMap;
public void run() {
detailMap = //here code for calling a class that will connect to database and process the result and return a "Map" .This will return within 30 second.If not i have to stop this thread.
setDetailsMap(detailMap);
pubilc void setName(String Name){
this.name = name;
public Map getDetailsMap(){
return detailMap;
Edited by: ragavarnan_call_screen on May 27, 2008 11:46 PM

First create a timer thread that fires after the time period and which can be cancelled.
If it fires (hasn't been cancelled) then one of the following must occur.
1. If and only if the driver/database is fixed and the driver supports the Statement.cancel() method then use it. You must test this and be sure to test for regular queries and procs as well.
2. Close the connection.

Similar Messages

  • Why can't I interrupt the main thread from a child thread with this code?

    I am trying to find an elegant way for a child thread (spawned from a main thread) to stop what its doing and tell the main thread something went wrong. I thought that if I invoke mainThread.interrupt() from the child thread by giving the child thread a reference to the main thread, that would do the trick. But it doesn't work all the time. I want to know why. Here's my code below:
    The main class:
    * IF YOU RUN THIS OFTEN ENOUGH, YOU'LL NOTICE THE "Child Please!" MESSAGE NOT SHOW AT SOME POINT. WHY?
    public class InterruptingParentFromChildThread
         public static void main( String args[] )
              Thread child = new Thread( new ChildThread( Thread.currentThread() ) );
              child.start();
              try
                   child.join();
              catch( InterruptedException e )
    // THE LINE BELOW DOESN'T GET PRINTED EVERY SINGLE TIME ALTHOUGH IT WORKS MOST TIMES, WHY?
                   System.out.println( "Child please!" );
              System.out.println( "ALL DONE!" );
    The class for the child thread:
    public class ChildThread implements Runnable
         Thread mParent;
         public ChildThread( Thread inParent )
              mParent = inParent;
         public void run()
              System.out.println( "In child thread." );
              System.out.println( "Let's interrupt the parent thread now." );
              // THE COMMENTED OUT LINE BELOW, IF UNCOMMENTED, DOESN'T INVOKE InterruptedException THAT CAN BE CAUGHT IN THE MAIN CLASS' CATCH BLOCK, WHY?
              //Thread.currentThread().interrupt();
              // THIS LINE BELOW ONLY WORKS SOMETIMES, WHY?
              mParent.interrupt();
    }

    EJP wrote:
    I'm not convinced about that. The wording in join() suggests that, but the wording in interrupt() definitely does not.Thread.join() doesn't really provide much in the way of details, but Object.wait() does:
    "throws InterruptedException - if any thread interrupted the current thread +before+ or while the current thread was waiting for a notification. The interrupted status of the current thread is cleared when this exception is thrown."
    every jdk method i've used which throws InterruptedException will always throw if entered while a thread is currently interrupted. admitted, i rarely use Thread.join(), so it's possible that method could be different. however, that makes the thread interruption far less useful if it's required to hit the thread while it's already paused.
    a simple test with Thread.sleep() confirms my expected behavior (sleep will throw):
    Thread.currentThread().interrupt();
    Thread.sleep(1000L);

  • Waiting the main thread till all child thread has completed

    I am in the process of developing a batch application in Java 5.0 which extensively uses the java.util.concurrency API. Here is a small description of what the batch process will do,
    1. Retrieve values from DB and populate a blocking queue in main thread.
    2. Instantiate a Threadpool by calling, Executors.newFixedThreadPool(2)
    3. Invoking the following block of code from the main thread,
    while(!iBlockingQueue.isEmpty()) {
        AbstractProcessor lProcessor = new  DefaultProcessor((BusinessObject)iBlockingQueue.remove());
        iThreadPool.execute(lProcessor);
    }DefaultProcessor is a class that extends Thread.
    4. Invoking the following block of code from the main thread,
    iThreadPool.shutdown();
    try {
         iThreadPool.awaitTermination(30, TimeUnit.SECONDS);
         } catch (InterruptedException interruptedException) {
              iLogger.debug("Error in await termination...", interruptedException);
    Since, this is the first time I am using the java.util.concurrency API, I want to know whether this is the right way to wait for all the child threads to complete before executing further statements in the main (parent) thread. Or do I necessariliy have to call join() to ensure that the main thread waits for all the child threads to finish which can only happen when the queue is empty.
    Please note here that as per the requirements of the application the blocking queue is filled only once at the very beginning.
    I will appreciate any inputs on this.
    Thanks.

    looks like you would be waiting on a queue twice, once in the loop and again, under the hood, in the threadpool's execute()
    the threadpool's internal queue is all that is needed
    if your iBlockingQueue is also the threadpool's internal queue, you might have a problem when you remove() the BusinessObject
    by making DefaultProcessor extend Thread you are, in effect, implementing your own threadpool without the pooling
    DefaultProcessor need only implement Runnable, it will be wrapped in a thread within the pool and start() called
    to implement a clean shutdown, I suggest writing DefaultProcessor.run() as an infinite loop around the blocking queue poll(timeout) and a stop flag that is checked before going back to poll
    class DefaultProcessor implements Runnable {
      private BlockingQueue myQ;
      private boolean myStopFlag;
      DefaultProcessor( BlockingQueue bq ) { myQ = bq; }
      public void run() {
        BusinessObject bo = null;
        while( !myStopFlag && (bo=myQ.poll( 10, SECONDS )) ) {
          // business code here
      public void stop() { myStopFlag = true; }
    } Now, after iThreadPool.shutdown(), either call stop() on all DefaultProcessors (or alternatively send "poison" messages to the queue), and give yourself enough time to allow processing to finish.

  • Running bat file in Child Thread

    Hi
    Please first of all i will tell you my application flow.
    I have an application you can say Parent Process/application , In execution of this Process or thread my application start/run batch file before dying using "exec() funtion" .In batch i have some scripts.and after initiating batch command my application main process ends up.
    Now problem is
    I am not sure that child process or Batch script which main program called is alive when my main application closed or its running?
    i want to see its output on console?
    Is it possible that Parent Thread ends up and child is still running , how can i achieve this .
    OR is it possible that i create seprate thread to start batch and my main thread ends. and i will show batch file output on console.

    I'm having a hard time understanding what you're
    saying, so here are a few general things that may be
    relevant:Sorry for that , well you are very much near which i want.But Thanks
    * Child threads can keep running after the thread
    that spawned them dies. You don't need to do anything
    special here.
    * The VM will exit when there are no more non-daemon
    threads running. So if you make all threads other
    than your main thread daemons, then when main ends,
    the rest of the threads will die and the VM will
    exit. See Thread.setDaemon.Here in above two point i have confusion.that by VM you mean Parent process,
    VM is parent process of all java programs that we run.please clarify this
    Lets say VM is parent process than your first statement is no valid as in first you say that parent die it will not effect child threads.
    well i have test this case with my program i write a program like
    public class ThreadTest
         public static void main(String [] arg)
              Work work=new Work(1000);
              System.out.println("Main Thread Started"+work.isDaemon());
              work.setDaemon(false);
              work.start();
              System.out.println("Main Thread stopped");
    class Work extends Thread
         int count=0;
         public Work(int cou)
              super("Workere");
              count=cou;
         public void run()
              while(count-->0)
                   System.err.println("Worker Thread is running................");
    }Now bydefault work thread is deamon,when all work thread steps executed program finished, tell me here as its concurent execution,
    main is alive or die when it execute its all statements or it waits for work thread which it spawned.
    Secondly when i change deamon to true, when main statements finished it also stoped work thread.mean work thread just print some messages.
    Actually what i want is that, when my main progam ends up, before ending it spawned new thread which start batch script and i want to see its output on seprate screen just like when we run IE with exec it starts IE window.
    Hope fully this time its clear

  • Closing all child threads when closing the stage

    I have multiple instances of child threads which are started and should continue to execute in till the applications exits.
    I have classes which extends Task and I create the threads as
    new Thread(object of the class).start();
    when it comes to interrupting/stoping (dont know which one is correct, please let me know) the threads which should be done inside
    primaryStage.onCloseOperation(){}
    here i want to end all child threads but since my threads are spreaded across different classes, my not having a clear picture how to achieve this.
    I know there is some designing problem, in my application, when it comes to threads, but I am not able to figure out how to resolve out.

    Use thread.setDaemon(true) Thread (Java Platform SE 7 )
    I suggest to use the Executor Framework and a ThreadFactory, to only need to create a daemon thread once.
    Something like this:
    Executor executor = Executors.newCachedThreadPool(new ThreadFactory() {
                @Override
                public Thread newThread(Runnable r) {
                    Thread thread = new Thread(r);
                    thread.setDaemon(true);
                    return thread;
    And then use it like this:
    executor.execute(yourTaskOrRunnable);
    When there are only daemon threads running, the JVM will halt and also stop all daemon threads.

  • How can I stop my childs ipod and ipad receiving same messages

    how can I stop my childs ipod and ipad receiving same messages, they were both set up to the same email account and itunes account. I have just set up a new itunes account for my daughters ipod and changed hers to the new account but my ipad still seems to be getting the same messages from her ipod which is what I wanted to avoid, any suggestions ?
    Mel X

    i  changed  itunes and email password. and afew others  will that stop the text messages form going to it.

  • How to kill parent and child thread in sequnece

    Hello freinds,
    I have one class FirstClass which creates one thread Pserver and Pserver creates three threads then how to kill parent Pserver and child threads.........

    define a method that requests that the parent thread terminate itself, and within the code called when the thread is shutting itself down, have it do something similar to its child threads: call methods that request they shutdown themselves.
    One common way to do this is to interrupt the thread.

  • Stop an OSGi thread

    Hi everyone!
    I am programming a OSGi bundle using Eclipse. The problem is that I don't know how to use the stop method in the Activator class so my program does never stop and I have to stop it by hand. For example:
    public void start(BundleContext context) throws Exception {
          System.out.println("Starting bundle"); }
    public void stop(BundleContext context) throws Exception {
         }The console shows the Starting bundle message but instead of stopping the program after doing the only thing it must do, it does not stop. What should I write in the stop thread so that the program after showing the message stops?
    Thanks in advance!

    What exactly are you trying to do? Calling Thread.stop( ) is inherently a bad idea (see the Javadocs).
    You are getting a IllegalStateException because Thread.stop( ) kills the thread, you would need to create a new thread to resume execution.
    If what you are trying to do is pause execution, you probably want to redesign your thread's tasks into smaller chunks that can be launched separately. Alternatively, have the thread check it's interrupted state and if a flag was set block on a monitor until you want it to resume execution.

  • Cannot stop memory monitor thread

    Hi All,
    I am getting the following error intermittently in a dataflow which has degree of parallelism = 8.
    22943 0 SYS-170111 27/11/2009 12:22:05 |SubDataflow DF_Conform_ISI_Person_Match_Prep_1_9
    22943 0 SYS-170111 27/11/2009 12:22:05 Cannot stop memory monitor thread: <RWThreadImp::terminate - No thread is active within the runnable>
    Any ideas as to the cause ?
    Thanks,
    Eric Jones.

    We are having the same issue.
    According to ADAPT00890818, this issue should be resolved in 12.0.0. We are currently running with version 12.2.2.3.
    Please advice.

  • 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?

  • Initialize QTMovie in a child thread by passing Movie object.

    I'm working on an Qt (Qt framework) application in which I'm making use of a .mm file to call MAC specific functions.
    I need to initialize QTMovie in a child thread by passing Movie object.
    [QTMovie movieWithQuickTimeMovie:movie disposeWhenDone:TRUE error:nil]
    It appears like I have to initialize QTMovie in main thread. I came across performSelectorOnMainThread which might be of some help. Could anyone please show me the right usage of the same?
    I need to call a method using performSelectorOnMainThread by passing the Movie object to it and which returns the initialized QTMovie object.
    Thanks in advance.

    Ah, you seem to be on to something, there. The main thread gives
    sun.misc.Launcher$AppClassLoader@111f71
    while the child thread gives null. The same occurs whether the experiment is in
    the same JVM instance or not.
    So presumably this means I need to get the context loader from the main thread
    and set it in the child thread manually!?
    - Angus.
    Patrick Linskey wrote:
    Angus Monro <[email protected]> writes:
    Okay.... I'm not really sure what you're asking for. What I've done is
    printed the ClassLoader object as given by
    com.solarmetric.util.app.Prefs.class.getClassLoader(), along with its
    parent recursively up the tree of loaders. This gave:
    sun.misc.Launcher$AppClassLoader@111f71
    sun.misc.Launcher$ExtClassLoader@256a7c
    This result was exactly the same irrespective of whether I did it from the
    main thread or the child thread. But the exception still happens only the
    child thread.Sorry, I should have been more clear. Can you print out the current
    thread's context's classloader?
    System.out.println (Thread.currentThread ().getContextClassLoader ());
    Also, what happens if you run the test in the main thread and then in
    the child thread, all in the same JVM?
    -Patrick
    - Angus.
    Patrick Linskey [email protected]
    SolarMetric Inc. http://www.solarmetric.com

  • Exceptions in child thread

    Hello,
    I am writing a few classes that i plan on reusing a lot. The classes create
    child threads that do ... work. If a exception is cought in one of the child threads
    I want to send it up to the caller. I can't declare the run() method of a thread to throw
    an exception ... so could someone suggest a nice clean way to get the cought exception back to the caller.
    Thanks,
    jd

    To answer that question, you need to think about what the "caller" (the parent thread) is doing while the child thread is executing.
    Is it waiting in a join() call?
    Is it doing its own processing?
    What do you expect it to do when a child thread throws an exception?
    (The answer to the bolded questions may drive how you report the exception back to the parent thread.)
    With a typical single-threaded chain of calls, when an exception is encountered, there is a well defined stack back to the main() method--main called foo which called bar which called baz, etc. In a multithreaded context, the parent thread could potentially be executing any of its instructions when the exception occurs. Remember, the parent thread and child thread are executing independently of each other.

  • TIme taken by Child threads to execute

    Hi
    I have a small query related to multithreading. I have a main thread launching a few Child threads. Now I want to check how much time all the 10000 child threads are taking to execute. I cannot write a System.currentTimeMillis(); before a main thread exits because I want the Child threads to keep executing even after the Main thread exits because I do not know how much time the child threads will take. I have made the child threads as non-deamon
    class ChildThread implements Runnable {
         Thread t;
         int i;
         ChildThread(int i) {
              t = new Thread(this, "SMS Thread");
              this.i = i;
              t.setDaemon(false);
              t.start();
         public void run() {
              try {
                   System.out.println(i);
              } catch (Exception smsex) {
                   System.out.println("Exception occured while sending message :"
                             + smsex.getMessage());
                   smsex.printStackTrace();
    public class MainThread {
         public static void main(String args[]) {
              long start = System.currentTimeMillis();
              ChildThread thread = null;
              try {
                   for (int i = 10000; i > 0; i--) {
                        thread = new ChildThread(i); // create a new thread
              } catch (Exception e) {
                   System.out.println("Main thread interrupted.");
              long end = System.currentTimeMillis();
              System.out.println("Main thread exiting. Took " + (end - start)
                        + " ms.");
    }

    This is a sample i have assumed.. dont have the complete code.
    I will just explain this
    Create an executor service object in a class called ThreadDispatcher.
    And create your chileThread as given below
    class ChildThread implements Runnable {
         ChildThread() {                    
         public void run() {
              try {
                   System.out.println(i);
              } catch (Exception smsex) {
                   System.out.println("Exception occured while sending message :"
                             + smsex.getMessage());
                   smsex.printStackTrace();
    }And the ThreadDispatcher class as below -This is just to beautify the code :)
    public class ThreadUtil {
    private static ExecutorService exec = Executors.newFixedThreadPool(some_value);
    public static List<Future> executionResults = new ArrayList<Future>();
    }And finaly come to the main Thread class
    public class MainThread {
         public static void main(String args[]) {
              ChildThread thread = null;
              try {
                             long start = System.currentTimeMillis();
                   for (int i = 10000; i > 0; i--) {
                        thread = new ChildThread(i); // create a new thread
                                    ThreadDispatcher.executionResults.add(ThreadDispatcher.exec.submit(thread));
              } catch (Exception e) {
                   System.out.println("Main thread interrupted.");
                    //Here place the while loop to check each thread status
                     while (ThreadDispatcher.executionResults.size() > 0) {
                   try {
                        Future task = ThreadDispatcher.executionResults.get(0);
                        task.get();//Wait until the thread finishes execution
                                    ThreadDispatcher.executionResults.remove(task);
                   } catch (InterruptedException e) {
                        e.printStackTrace();
                   } catch (ExecutionException e) {
                        e.printStackTrace();
              long end = System.currentTimeMillis(); //This time will probably be the end time.
              System.out.println("Main thread exiting. Took " + (end - start)
                        + " ms.");
    }Hope this will be helpful...

  • SYS-170111 - Cannot stop memory monitor thread: RWThreadImp::terminate -

    Hi Experts,
                  WE have this warning in pretty much every job in production. But the warnings are not specific to certain jobs they might occur one day and not the other day.
    Cannot stop memory monitor thread: <RWThreadImp::terminate - No thread is active within the runnable>.
    I know looking at the release notes this issue was fixed in 3.0 (12.0.0), we are using 3.2 (12.2.0) and having the same issues. The job server is on a linux 64 bit. I have not seen this issue in any of our windows job server. Is this bug specific to linux or is there a resolution for this.
    Appreciate your help in advance.
    Thanks
    AJ
    Edited by: alangilbi on Sep 28, 2011 5:17 PM

    Hi, AJ.
    As can be seen in the KBA 1455412 this is a known behavior.
    "As a result of fixing the problem identified in ADAPT 00890818 in release 12.0.0.0, this message is displayed by design. If there is really a problem in stopping the memory monitor thread an exception is thrown and an error message is logged.
    Background:
    In the memory monitor's shutdown logic, once it tells the monitor thread to shutdown it waits for the thread to terminate but only for 10 seconds. It could be that at this same time the wait expired when the thread actually terminates. So when this happens in the shutdown logic we force terminate the thread. Since there is no active thread anymore the terminate call throws an exception and then we catch it and then throws the error for the job."
    You can just ignore this warning.
    Leo.

  • How do I STOP & DESTROY a thread?????

    I cannot seem to get my wait cursor to work. Sometimes it appears, sometimes it doesn't. After searching the forums I saw that I must put my long computational code in a seperate thread to get my wait cursor to be painted...
    My question is: How do you stop & destroy a thread? Or will it automatically stop/destroy itself when done running?

    Currently, what I am doing is:
    //set cursor
    public void run() {
    //long process
    //set cursor to normal
    This seems to work fine, but I just wanted to make sure there is not stop/destory method. I didn't want 50 empty thread floating around. I am new to using threads...
    Thanks!

Maybe you are looking for

  • Importing songs from an external Hard Disk

    As I am using a laptop, with a small amount of hard disk space and due to my excessive amount ofmusic I wish to hold my music on a external hard disk (there for is not anywhere on the c:). However when I tried to import this music into my i-tunes lib

  • Af:query date attributes BUG in TP3

    Hello, I have found another bug in the af:query component. The date selectors that are rendered for every date attribute don't work, the calendar doesn't open when I click the calendar icon. Thanks, Marc

  • Illustrator v18.1.1 can't scale objects with pointer

    as of today, jan 19, 2014, using the object selection tool I cannot scale objects either individually or as a group! aaargh! it's a fairly necessary feature, anyone else having this issue?

  • Best codec for theatrical video?

    I shot a stage performance on a Sony DVCam (not HD) and want to preserve the highest quality. Can I do better than just creating it as a large movie? I will be burning it in iDVD at the highest setting there, even if I have to split it into 2 disks.

  • Could a change in the Windows operating system impact DAQ response?

    I use a PCI-6013 analog DAQ card (vintage 2002) to control and acquire data with a fairly old computer running Windows 2000. I installed the card in a newer computer running Windows XP. There were no other changes to software or hardware. The data no