Interface Metronome

Functional Interface:
This is a functional interface and can therefore be used as the assignment target for a lambda expression or method reference.

@FunctionalInterface public interface Metronome
A class that can be used to perform an action at a regular interval. To use, set up a Metronome instance and perform a repeated event (perhaps using a loop), calling pause() before each event.
Author:
Randall Hauch
  • Method Details

    • pause

      void pause() throws InterruptedException
      Pause until the next tick of the metronome.
      Throws:
      InterruptedException - if the thread was interrupted while pausing
    • sleeper

      static Metronome sleeper(Duration period, Clock timeSystem)
      Create a new metronome that starts ticking immediately and that uses Thread.sleep(long) to wait.

      Generally speaking, this is a simple but inaccurate approach for periods anywhere close to the precision of the supplied Clock (which for the system clock is typically around 10-15 milliseconds for modern Linux and OS X systems, and potentially worse on Windows and older Linux/Unix systems. And because this metronome uses Thread#sleep(long), thread context switches are likely and will negatively affect the precision of the metronome's period.

      Although the method seemingly supports taking TimeUnit.MICROSECONDS and TimeUnit.NANOSECONDS, it is likely that the JVM and operating system do not support such fine-grained precision. And as mentioned above, care should be used when specifying a period of 20 milliseconds or smaller.

      Parameters:
      period - the period of time that the metronome ticks and for which pause() waits
      timeSystem - the time system that will provide the current time; may not be null
      Returns:
      the new metronome; never null
    • parker

      static Metronome parker(Duration period, Clock timeSystem)
      Create a new metronome that starts ticking immediately and that uses LockSupport.parkNanos(long) to wait.

      LockSupport.parkNanos(long) uses the underlying platform-specific timed wait mechanism, which may be more accurate for smaller periods than sleeper(Duration, Clock). However, like sleeper(Duration, Clock), the resulting Metronome may result in thread context switches.

      Although the method seemingly supports taking TimeUnit.MICROSECONDS and TimeUnit.NANOSECONDS, it is likely that the JVM and operating system do not support such fine-grained precision. And as mentioned above, care should be used when specifying a period of 10-15 milliseconds or smaller.

      Parameters:
      period - the period of time that the metronome ticks and for which pause() waits
      timeSystem - the time system that will provide the current time; may not be null
      Returns:
      the new metronome; never null