Will Perone

The Problem:
J2ME's TimerTask is run on a background thread independant of the event thread thus causing potential synchronization problems with things like drawing to the screen etc.

The solution:
Derive from the TimerTask a threadsafe TimerTask that calls itself serially thus placing itself in the event thread. The following derived class has an option to run serialized on the event thread or as a normal TimerTask.

import java.util.TimerTask;
  
  
public class GeneralTimerTask extends TimerTask {    
    private boolean runOnEventThread;
    
    public GeneralTimerTask(boolean runOnEventThread) {
        this.runOnEventThread= runOnEventThread;
    }
    
    private Thread timerThread;

    public void run() {
    	if (timerThread == null) { // first run through will be on the timer thread
    		timerThread = Thread.currentThread();
    	}
    	if (timerThread==Thread.currentThread() && runOnEventThread) {
    		MApp.mainApp.d.callSerially(this);
    	} else {
	        (call whatever handler/function you want to execute here)
    	}
    }
}

Use this GeneralTimerTask just like any other TimerTask:

Timer timer;
GeneralTimerTask timerTask;
long updateDelay = 500; // milliseconds
... 
timerTask = new GeneralTimerTask(true);
timer.schedule(timerTask, updateDelay); // GeneralTimerTask:run will now be called every 500ms
...
timerTask.cancel();


2 Comments
fovqaslgmt 0 0
Hello! Good Site! Thanks you!
Rosalinda 2011/11/23 Contact Me11 0
I thought I'd have to read a book for a dsicveory like this!

<- for private contact