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.
Metronome
instance and perform
a repeated event (perhaps using a loop), calling pause()
before each event.- Author:
- Randall Hauch
-
Method Summary
Modifier and TypeMethodDescriptionstatic Metronome
Create a new metronome that starts ticking immediately and that usesLockSupport.parkNanos(long)
to wait.void
pause()
Pause until the next tick of the metronome.static Metronome
Create a new metronome that starts ticking immediately and that usesThread.sleep(long)
to wait.
-
Method Details
-
pause
Pause until the next tick of the metronome.- Throws:
InterruptedException
- if the thread was interrupted while pausing
-
sleeper
Create a new metronome that starts ticking immediately and that usesThread.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
andTimeUnit.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 aperiod
of 20 milliseconds or smaller.- Parameters:
period
- the period of time that the metronome ticks and for whichpause()
waitstimeSystem
- the time system that will provide the current time; may not be null- Returns:
- the new metronome; never null
-
parker
Create a new metronome that starts ticking immediately and that usesLockSupport.parkNanos(long)
to wait.LockSupport.parkNanos(long)
uses the underlying platform-specific timed wait mechanism, which may be more accurate for smaller periods thansleeper(Duration, Clock)
. However, likesleeper(Duration, Clock)
, the resulting Metronome may result in thread context switches.Although the method seemingly supports taking
TimeUnit.MICROSECONDS
andTimeUnit.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 aperiod
of 10-15 milliseconds or smaller.- Parameters:
period
- the period of time that the metronome ticks and for whichpause()
waitstimeSystem
- the time system that will provide the current time; may not be null- Returns:
- the new metronome; never null
-