//-------------------------------------------------------------------- // OffsetClock - A simple wrapper to simulate a settable clock // by maintaining an offset to the system clock. // // CSEP590SG Winter 2004 - University of Washington // Andy Collins - acollins@cs.washington.edu //-------------------------------------------------------------------- import java.util.*; import java.io.*; public class OffsetClock { // Create a clock with no extra drift, // and starting in sync with the system clock public OffsetClock () { offset = 0; rho = 0.0; lastRhoChangeActualTime = System.currentTimeMillis (); } // Create a clock with no extra drift, // but starting at the specified time public OffsetClock (long startTimeMS) { offset = startTimeMS - System.currentTimeMillis (); rho = 0.0; lastRhoChangeActualTime = System.currentTimeMillis (); } // Create a clock with extra drift, // and starting at the specified time public OffsetClock (double rhoValue, long startTimeMS) { offset = startTimeMS - System.currentTimeMillis (); rho = rhoValue; lastRhoChangeActualTime = System.currentTimeMillis (); } public synchronized void SetRho (double rhoValue) { rho = rhoValue; lastRhoChangeActualTime = System.currentTimeMillis (); } public synchronized long CurrentTimeMillis () { // Read the real clock. Note that this is itself subject // to error, a fact we studiously ignore in the hope that // our applied error will dominate. long actualTime = System.currentTimeMillis (); long reportedTime = actualTime + offset + (long) ((double) (actualTime - lastRhoChangeActualTime)*rho); return reportedTime; } public synchronized void SetCurrentTimeMillis (long newTime) { offset = newTime - System.currentTimeMillis (); } private double rho; private long lastRhoChangeActualTime; private long offset; }