Reputation: 7026
I am converting a swing application to GWT, that made heavy use of multithreading. The code runs a continuous numerical simulation in the background, and displays results graphically each frame. The simulation needs to know how much real time elapses on each calculation.
Thread calculate = new Thread(new Runnable(){
// run calculation cycles every 10 ms
// (or as fast as possible)
long prevT=System.currentTimeMillis();
while(!isFinished){
long currT = System.currentTimeMillis(),
dt = currT-prevT;
if(dt<10) Thread.sleep(5);
else{
simulate(dt);
prevT = currT;
}
}
}
// Update UI every 60 ms
java.awt.Timer timer = new Timer(60, new ActionListener(){public void actionPerformed(ActionEvent e){
results = getCurrentSimState();
uiPanel.render(results);
}});
Additionally there is event-driven code from the user that changes the simulator state.
What is the best way to implement this in GWT? Most previous multithreading questions relate primarily to async client-server work. I saw this question Threading in GWT (Client) and I wondered if a Scheduler
would be appropriate:
void onLoad(){
AnimationScheduler.get().requestAnimationFrame(callback, uiElement);
}
AnimationCallback cb = new AnimationCallback(){public void execute(double t){
results = getCurrentSimState();
render(results, uiElement);
AnimationScheduler.get().requestAnimationFrame(callback, uiElement);
}};
double prevT=Duration.currentTimeMillis();
Scheduler.get().scheduleIncremental(new RepeatingCommand(){ public void execute() {
double currT = Duration.currentTimeMillis(),
dt = currT-prevT;
if(dt>30){
calculate(dt);
prevT = currT;
}
return isFinished;
}});
As I'm completely new to GWT, I'd really like to know if
RepeatingCommand
, or the GUI update in the AnimationScheduler
? Upvotes: 0
Views: 379
Reputation: 41099
Instead of "simulating" multi-threading with Scheduler, you may want to consider using real background processing with Web Workers.
Note that with an Incremental command in Scheduler, you have to return "false" when the work is finished, or "true" when it needs to continue. This command will only work if you can split your calculations in small chunks, and then give back control to JavaScript between the chunks that it can execute user actions.
If you can't split the work in small chunks, the approach with a Scheduler will only work if each calculation cycle takes less time than the interval between calculations, giving JavaScript a chance to react to user activity between the calculations.
Upvotes: 1