views:

332

answers:

3

I have a long running task that is executing in the background on an ExecutorService thread pool. What are some best practices in terms of this task returning progress or intermediate results? Are there any libraries that provide this functionality?

EDIT: To clarify, I'm talking about reporting progress to other code, not to the user.

Normally I would use SwingWorker, but I'm working with a Java/Groovy backend for a Grails app, and I'm unsure how that would behave in a headless server environment since it has EDT ties.

Another example is the Jobs framework in Eclipse RCP, but I would need something that doesn't have ties to the UI.

+1  A: 

Why not just use a callback? When starting the background task, pass an object with a callback function to the task and let the task report progress that way. Without any involved UI you dont need to change thread to do so.

Adrian
+2  A: 

Hey you could possibly try and implement the Observer Pattern and have interested parties subscribe to the worker thread (extension of java.util.Observable or similar) or another Class that manages the observers.

You could use java.util.Observer and java.util.Observable or roll your own.

Simple Example of some Interfaces implementing the Observer Pattern:

public interface ObservableSubject<T extends SubjectObserver, V> {

   void registerObserver(T observer);

   void removeObserver(T observer);

   void notifyObservers(V notificationPayload); 

}


public interface SubjectObserver<T> {

   void handleNotification(T notificationPayload);
}

More info: Observer Pattern on Wikipedia

edwardTheGreat
A: 

The answers from Adrian and edwardTheGreat are both good options. It all depends on how you want the "other code" to consume status updates. A third option is to use a message queue into which the background thread writes periodic status. A really general version of this would use JMS.

Jim Garrison