PDA

View Full Version : Rich client and scheduling



Patrick Vanhuyse
Oct 11th, 2004, 09:10 AM
I would have code like :



interface JobListener {
void begin();
void end();
void completed(int percent);
}

class Job extends TimerTask {
JobListener listener;

void run() {
listener.begin();
for (...) {
listener.completed(i);
}
listener.end();
}
}

class View extends AbstractView implements JobListener {
void begin() {
getStatusBar().setMessage("Begin"); // And/or other Swing stuff
}
void end() {
getStatusBar().setMessage("End"); // And/or other Swing stuff
}
void completed(int percent) {
getStatusBar().setMessage("Completed " + percent); // And/or other Swing stuff
}
}


The job is scheduled using Spring Framework (org.springframework.scheduling.timer).

Since the job doesn't run in the Swing's thread, shouldn't this cause problem with Swing ?

I think it would.
How can I do that ?

Keith Donald
Oct 11th, 2004, 04:19 PM
Yes, updating a swing widget in any thread but the event dispatching thread will cause a problem (flickering and the like.) The simplest solution is to use SwingUtilities.invokeLater(Runnable), to force execution in the event dispatching thread.

I wonder if Foxtrot would help out here.

Patrick Vanhuyse
Oct 12th, 2004, 02:38 AM
There is also http://spin.sourceforge.net

I think these API can help to run long task from Swing.
Here I want to run a short task in the Swing thread from another thread.

Here is my code :


interface JobListener {
void begin();
void end();
void completed(int percent);
}

class Job extends TimerTask {
JobListener listener;

void run() {
doInSwing(new Runnable() { listener.begin(); });
for (...) {
doInSwing(new Runnable() { listener.completed(); });
}
doInSwing(new Runnable() { listener.end(); });
}

private void doInSwing(Runnable runnable) {
try {
SwingUtilities.invokeAndWait(runnable);
} catch (InterruptedException e) {
// Logging
} catch (InvocationTargetException e) {
// Logging
}
}
}

class View extends AbstractView implements JobListener {
void begin() {
getStatusBar().setMessage("Begin"); // And/or other Swing stuff
}
void end() {
getStatusBar().setMessage("End"); // And/or other Swing stuff
}
void completed(int percent) {
getStatusBar().setMessage("Completed " + percent); // And/or other Swing stuff
}
}


Could be better if Swing handled multi-threading ! :wink:

Patrick Vanhuyse
Oct 12th, 2004, 02:57 AM
Easier solution using Spin.

The code from first post unchanged.

Call to setJobListener :

job.setJobListener((JobListener) Spin.over(view));

oliverhutchison
Oct 12th, 2004, 07:11 AM
Cool!

I've been meaning to look at Spin for some time. I had no idea it had this Spin.over funtionality IMO even more usfull than Spin.off. It's also a great little example of where AOP realy shines.

Thanks for pointing that out

Ollie