Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

java background task

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.

like image 512
markovuksanovic Avatar asked May 10 '10 16:05

markovuksanovic


2 Answers

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();
like image 155
Michael Mrozek Avatar answered Sep 24 '22 14:09

Michael Mrozek


You should use Thread Pools,

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

like image 30
ZZ Coder Avatar answered Sep 26 '22 14:09

ZZ Coder