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.
Swing
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:
GWT
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
- is this a feasible design? It is very confusing going from threaded to event-driven design.
- I've no idea which one is likely to be "ticking" faster. Which of the two things gets prioritised? The calculation in the
RepeatingCommand
, or the GUI update in theAnimationScheduler
? - Are there any major caveats with this design? I don't want the page to lock up! I arbitrarily chose to use different ways of scheduling for the two threads -- is that correct? And if so why?
- 10 ms might be to fast, but is there a way of guessing what a sensible calculation rate is? The simulator is more accurate the faster it can be updated. (It is a system of stiff PDEs solved by RK4!)