views:

57

answers:

3

I'm aware of this question here but I have a slightly different question. If I wish to hand-code via the various Thread methods myself (not via utility classes or Quartz) the running of a Thread at a particular time, then what would be the most efficient (in terms of overhead) to code this.

I considered:

    boolean wasInterrupted = false;

    while (System.currentTimeMillis() < executionTimeInMillis) {
        try {
            Thread.sleep(X);
        } catch (InterruptedException ie) {
            wasInterrupted = true;
        }
    }

    if (!wasInterrupted) {
        doMyThing();
    }

Is there a better way? Is this primitive and naive?

A: 

Try to think about efficiency last. I use the following maxima:

  1. Write the code that works
  2. Modify the code so that it works correctly
  3. If and only if this code runs slow (use profiling tools for that) modify the code so that it works fast.

And remember, premature optimization is the root of all evil.

zamza
+2  A: 

You have three basic possibilities:

  • Thread.sleep(...): causes the currently executing thread to sleep (cease execution) for the specified number of milliseconds plus the specified number of nanoseconds, subject to the precision and accuracy of system timers and schedulers. The thread does not lose ownership of any monitors;
  • Thread.yield(): causes the currently executing thread object to temporarily pause and allow other threads to execute;
  • Monitors: you call wait on the object you want to lock and you release the lock by calling notify on the same object. For more information look at the javadoc: http://download.oracle.com/docs/cd/E17409_01/javase/6/docs/api/java/lang/Object.html#wait()

The best way is to use monitors because you know when you acquire lock and when you release it. Moreover, it allows to let other threads to execute. If you want to understand why sleep and yield methods must be avoid, read http://www.javamex.com/tutorials/threads/yield.shtml.

Laurent
A: 

I would use a Timer/TimerTask combination, starting the thread you want to run in the run() method of the TimerTask (Alternatively, you could just do the work directly in the TimerTask's run() method, which will then be performed in the Timer's thread). That approach doesn't need try/catch blocks or a while loop, and strikes me as a bit more direct.

Check out:

http://download.oracle.com/docs/cd/E17476_01/javase/1.4.2/docs/api/java/util/Timer.html

http://download.oracle.com/docs/cd/E17476_01/javase/1.4.2/docs/api/java/util/TimerTask.html

SirBoss