tags:

views:

34

answers:

1

In a desktop Java 1.5 application (it has to run on a lot of MacOS X machines that will nerver see a 1.6 VM due to Apple politics) what is a correct way to perform a lengthy computation outside the EDT?

Say, for example, when the user clicks on a button that starts an operation: I get the notification on the EDT and I want to run some method (say crunchData() ).

Here's one way to do it:

        final Thread t = new Thread( new Runnable() {
            public void run() {
                crunchData();
            }
        } );
        t.start;

I mean: this does what I want but every single time the user starts a potentially long running task I use the above idiom. And I feel like I'm always unnecessarily creating lots of task (moreover altough sometimes the operation can be lenghty, sometimes it won't and in these case I'd like the app as responsible as possible).

Another way to do it would be to have another (non-EDT) thread (or a pool of threads), always running, say waiting on a blocking queue and executing, say, Runnable that I would enqueue wherever I need to perform a lenghty operation.

What is the correct way to deal with this?

EDIT Is the correct way to deal with something that simple to install SwingWorker? How did people deal with this (which seems pretty basic) before SwingWorker came?

+3  A: 

The recommended way is to have your EDT code start a SwingWorker, which will do the job outside and return the result to you.

Riduidel
@Riduidel: I'm on Java 5 (this has to run on a lot of MacOS X computers that will never ever get Java 6... Thanks Apple ;)
NoozNooz42
@NoozNooz42 - you can get code for the old tutorial version of SwingWorker and use it, though. It's still floating out there and was still a standard pre Java 6.
justkt
Like @justkt mentionned, SwingWorker existed before Java 6. You can always grab the code (for example here : http://www.koders.com/java/fidAC10A778A6FF41B6C3229B820BF3C864C4BF019F.aspx?s=swingworker) and backport it to Java 5.
Riduidel