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.
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
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();
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.
You should use Thread Pools,
http://java.sun.com/docs/books/tutorial/essential/concurrency/pools.html
Make a thread. Mark this thread as Daemon. The JVM exits when the only thread running are all daemon threads.