views:

116

answers:

4

I have a function that needs to perfom two operations, one which finishes fast and one which takes a long time to run. I want to be able to delegate the long running operation to a thread and I dont care when the thread finishes, but the threads needs to complete. I implemented this as shown below , but, my secondoperation never gets done as the function exits after the start() call. How I can ensure that the function returns but the second operation thread finishes its execution as well and is not dependent on the parent thread ?

public void someFunction(String data)
{
   smallOperation()
   SecondOperation a = new SecondOperation();
   Thread th = new Thread(a);
   th.Start();
}

class SecondOperation implements Runnable
{
  public void run(){
  // doSomething long running
 }
} 
+1  A: 

The JVM will not exit before the thread terminates. This code that you posted does not even compile; perhaps the problem is in your actual code.

danben
I have written only the logical part of the code.
Ritesh M Nayak
I don't have any idea what you mean by "the logical part", but the code that you have provided is not the part that is causing your thread to terminate.
danben
A: 

IF your second function is not getting done it has nothing to do with your function returning. If something calls System.exit() or if your function throws an exception, then the thread will stop. Otherwise, it will run until it is complete, even if your main thread stops. That can be prevented by setting the new thread to be a daemon, but you are not doing that here.

Yishai
How do I set the new thread as a daemon?
Ritesh M Nayak
Just to be clear, setting it to a daemon will cause the JVM to exit before it is finished if no other non-daemon threads are running. So it is the opposite of what you want. You set it by calling setDaemon(true) on the Thread object *before* calling start().
Yishai
A: 

If you are deploying a webapp you can use Quartz to schedule and trigger the second operation to run asynchronously

jimi
This is a great example of overengineering. You do not need Quartz to utilize threads in Java.
danben
I agree completely with danben here.
John V.
+2  A: 
public void someFunction(final String data) {
    shortOperation(data);
    new Thread(new Runnable() {
        public void run(){
            longOperation(data);
        }
    }).start();
}

If someFunction is called, the JVM will run the longOperation if

  1. the thread running it is not marked as a daemon (in the above code it is not)
  2. the longOperation() does not throw an exception and
  3. no calls to System.exit() is made in longOperation()
binil