1

I've written a class to continue a started JAVA application if the current second is a multiple of 5 (i.e. Calender.SECOND % 5 == 0)

The class code is presented below, what I'm curious about is, am I doing this the right way? It doesn't seem like an elegant solution, blocking the execution like this and getting the instance over and over.

public class Synchronizer{
    private static Calendar c;

    public static void timeInSync(){
        do{
            c = Calendar.getInstance();
        }
        while(c.get(Calendar.SECOND) % 5 != 0);
    }
}

Synchronizer.timeInSync() is called in another class's constructor and an instance of that class is created at the start of the main method. Then the application runs forever with a TimerTask that's called every 5 seconds.

Is there a cleaner solution for synchronizing the time?

Update:

I think I did not clearly stated but what I'm looking for here is to synchronization with the system time without doing busy waiting.

So I need to be able to get

12:19:00
12:19:05
12:19:10
...
saccu
  • 117
  • 1
  • 2
  • 7
  • Are you familiar with System.currentTimeMillis? – Chris K Sep 23 '14 at 14:22
  • You could alternatively use [Timer](http://docs.oracle.com/javase/7/docs/api/java/util/Timer.html) since that's what it's designed for. – Compass Sep 23 '14 at 17:42
  • I've updated the question for a clearer question but Durandal's explanatory answer is very satisfactory to me. – saccu Sep 24 '14 at 09:26

4 Answers4

4

What you have now is called busy waiting (also sometimes referred as polling), and yes its inefficient in terms of processor usage and also in terms of energy usage. You code executes whenever the OS allows it, and in doing so it prevents the use of a CPU for other work, or when there is no other work it prevents the CPU from taking a nap, wasting energy (heating the CPU, draining the battery...).

What you should do is put your thread to sleep until the time where you want to do something arrives. This allows the CPU to perform other tasks or go to sleep.

There is a method on java.lang.Thread to do just that: Thread.sleep(long milliseconds) (it also has a cousin taking an additional nanos parameter, but the nanos may be ignored by the VM, and that kind of precision is rarely needed).

So first you determine when you need to do some work. Then you sleep until then. A naive implementation could look like that:

public static void waitUntil(long timestamp) {
    long millis = timestamp - System.currentTimeMillis();
    // return immediately if time is already in the past
    if (millis <= 0)
        return;
    try {
        Thread.sleep(millis);
    } catch (InterruptedException e) {
        throw new RuntimeException(e.getMessage(), e);
    }
}

This works fine if you don't have too strict requirements on precisely hitting the time, you can expect it to return reasonably close to the specified time (a few ten ms away probably) if the time isn't too far in the future (a few secs tops). You have however no guarantees that occasionally when the OS is really busy that it possily returns much later.

A slightly more accurate method is to determine the reuired sleep time, sleep for half the time, evaluate required sleep again, sleep again half the time and so on until the required sleep time becomes very small, then busy wait the remaining few milliseconds.

However System.currentTimeMillis() does not guarantee the actual resolution of time; it may change once every millisecond, but it might as well only change every ten ms by 10 (this depends on the platform). Same goes for System.nanoTime().

Waiting for an exact point in time is not possible in high level programming languages in a multi-tasking environment (practically everywhere nowadays). If you have strict requirements, you need to turn to the operating system specifics to create an interrupt at the specified time and handle the event in the interrupt (that means assembler or at least C for the interrupt handler). You won't need that in most normal applications, a few ms +/- usually don't matter in a game/application.

Durandal
  • 19,919
  • 4
  • 36
  • 70
1

As @ChrisK suggests, you could simplify by just making a direct call to System.currentTimeMillis().

For example:

    long time = 0;
    do
    {
        time = System.currentTimeMillis();

    } while (time % 5000 != 0);

Note that you need to change the comparison value to 5000 because the representation of the time is in milliseconds.

Also, there are possible pitfalls to doing any comparison so directly like this, as the looping call depends on processor availability and whatnot, so there is a chance that an implementation such as this could make one call that returns:

`1411482384999`

And then the next call in the loop return

`1411482385001`

Meaning that your condition has been skipped by virtue of hardware availability.

If you want to use a built in scheduler, I suggest looking at the answer to a similar question here java: run a function after a specific number of seconds

Community
  • 1
  • 1
user3062946
  • 682
  • 1
  • 6
  • 17
0

You should use

System.nanoTime() 

instead of

System.currentTimeMillis()

because it returns the measured elapsed time instead of the system time, so nanoTime is not influenced by system time changes.

public class Synchronizer
{
    public static void timeInSync()
    {
        long lastNanoTime = System.nanoTime();
        long nowTime = System.nanoTime();
        while(nowTime/1000000 - lastNanoTime /1000000 < 5000 )
        {
            nowTime = System.nanoTime();
        }    
    }
}
NFoerster
  • 386
  • 2
  • 16
0

The first main point is that you must never use busy-waiting. In java you can avoid busy-waiting by using either Object.wait(timeout) or Thread.sleep(timeout). The later is more suitable for your case, because your case doesn't require losing monitor lock.

Next, you can use two approaches to wait until your time condition is satisfied. You can either precalculate your whole wait time or wait for small time intervals in loop, checking the condition.

I will illustrate both approaches here:

        private static long nextWakeTime(long time) {
            if (time / 1000 % 5 == 0) { // current time is multiple of five seconds
                return time;
            }
            return (time / 1000 / 5 + 1) * 5000;
        }


        private static void waitUsingCalculatedTime() {
            long currentTime = System.currentTimeMillis();
            long wakeTime = nextWakeTime(currentTime);

            while (currentTime < wakeTime) {
                try {
                    System.out.printf("Current time: %d%n", currentTime);
                    System.out.printf("Wake time: %d%n", wakeTime);
                    System.out.printf("Waiting: %d ms%n", wakeTime - currentTime);
                    Thread.sleep(wakeTime - currentTime);
                } catch (InterruptedException e) {
                    // ignore
                }
                currentTime = System.currentTimeMillis();
            }
        }

        private static void waitUsingSmallTime() {
            while (System.currentTimeMillis() / 1000 % 5 != 0) {
                try {
                    System.out.printf("Current time: %d%n", System.currentTimeMillis());
                    Thread.sleep(100);
                } catch (InterruptedException e) {
                    // ignore
                }
            }
        }

As you can see, waiting for the precalculated time is more complex, but it is more precise and more efficient (since in general case it will be done in single iteration). Waiting iteratively for small time interval is simpler, but less efficient and precise (precision is dependent on the selected size of the time interval).

Also please note how I calculate if the time condition is satisfied:

 (time / 1000 % 5 == 0)

In first step you need to calculate seconds and only then check if the are multiple of five. Checking by time % 5000 == 0 as suggested in other answer is wrong, as it is true only for the first millisecond of each fifth second.

Aivean
  • 10,692
  • 25
  • 39