001 package com.croftsoft.core.util.loop;
002
003 import com.croftsoft.core.math.MathConstants;
004
005 /*********************************************************************
006 * Maintains a periodic rate by stalling the loop by a fixed delay.
007 *
008 * @author
009 * <a href="http://www.CroftSoft.com/">David Wallace Croft</a>
010 * @version
011 * 2003-05-22
012 * @since
013 * 2002-03-07
014 *********************************************************************/
015
016 public final class FixedDelayLoopGovernor
017 implements LoopGovernor
018 //////////////////////////////////////////////////////////////////////
019 //////////////////////////////////////////////////////////////////////
020 {
021
022 private final long delayMillis;
023
024 private final int delayNanos;
025
026 //////////////////////////////////////////////////////////////////////
027 // constructor methods
028 //////////////////////////////////////////////////////////////////////
029
030 public FixedDelayLoopGovernor (
031 long delayMillis,
032 int delayNanos )
033 //////////////////////////////////////////////////////////////////////
034 {
035 this.delayMillis = delayMillis;
036
037 this.delayNanos = delayNanos;
038 }
039
040 /*********************************************************************
041 * Constructs a LoopGovernor with the specified target frequency.
042 *
043 * @param frequency
044 *
045 * The targeted loop frequency in loops per second.
046 *********************************************************************/
047 public FixedDelayLoopGovernor ( double frequency )
048 //////////////////////////////////////////////////////////////////////
049 {
050 if ( frequency <= 0.0 )
051 {
052 throw new IllegalArgumentException ( "frequency <= 0.0" );
053 }
054
055 long periodNanos
056 = ( long ) ( MathConstants.NANOSECONDS_PER_SECOND / frequency );
057
058 delayMillis
059 = periodNanos / MathConstants.NANOSECONDS_PER_MILLISECOND;
060
061 delayNanos = ( int )
062 ( periodNanos % MathConstants.NANOSECONDS_PER_MILLISECOND );
063 }
064
065 //////////////////////////////////////////////////////////////////////
066 //////////////////////////////////////////////////////////////////////
067
068 /*********************************************************************
069 * Stalls the current Thread by the fixed delay period.
070 *********************************************************************/
071 public void govern ( )
072 throws InterruptedException
073 //////////////////////////////////////////////////////////////////////
074 {
075 Thread.sleep ( delayMillis, delayNanos );
076 }
077
078 //////////////////////////////////////////////////////////////////////
079 //////////////////////////////////////////////////////////////////////
080 }