views:

118

answers:

5

I was wondering which would be the most efficient approach to implement some kind of background task in java (I guess that would be some kind of nonblocking Threads). To be more precise - I have some java code and then at some point I need to execute a long running operation. What I would like to do is to execute that operation in the background so that the rest of the program can continue executing and when that task is completed just update some specific object which. This change would be then detected by other components.

A: 

Naïve idea : you might be able to create Thread, give it a low priority, and do a loop of :

  • doing a little bit of work
  • using yield or sleep to let other threads work in parrallel

That would depend on what you actually want to do in your thread

phtrivier
+1  A: 

You want to make a new thread; depending on how long the method needs to be, you can make it inline:

// some code
new Thread(new Runnable() {
    @Override public void run() {
        // do stuff in this thread
    }
}).start();

Or just make a new class:

public class MyWorker extends Thread {
    public void run() {
        // do stuff in this thread
    }
}

// some code
new MyWorker().start();
Michael Mrozek
Wouldn't it be possible here that the long-running thread steals CPU and don't let the other threads run ?
phtrivier
Creating new Threads is discouraged in JEE.
Wes
A: 

Yes, you're going to want to spin the operation off on to it's own thread. Adding new threads can be a little dangerous if you aren't careful and aware of what that means and how resources will interact. Here is a good introduction to threads to help you get started.

Ryan Elkins
+1  A: 

You should use Thread Pools,

http://java.sun.com/docs/books/tutorial/essential/concurrency/pools.html

ZZ Coder
Yeah, this is what I was looking for, more specifically Executors,.. Thanks.
markovuksanovic
Could you put in an answer of your own about executors. I was about to ask a very similar question. I think Executors should be mentioned as a specific answer. I'd give it an upvote. I don't want to put an answer in to point steal.Especially as JEE discourages the spawning of new Threads.
Wes
A: 

Make a thread. Mark this thread as Daemon. The JVM exits when the only thread running are all daemon threads.

pritam potnis