1   /**
2    * Distribution License:
3    * JSword is free software; you can redistribute it and/or modify it under
4    * the terms of the GNU Lesser General Public License, version 2.1 or later
5    * as published by the Free Software Foundation. This program is distributed
6    * in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even
7    * the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
8    * See the GNU Lesser General Public License for more details.
9    *
10   * The License is available on the internet at:
11   *      http://www.gnu.org/copyleft/lgpl.html
12   * or by writing to:
13   *      Free Software Foundation, Inc.
14   *      59 Temple Place - Suite 330
15   *      Boston, MA 02111-1307, USA
16   *
17   * © CrossWire Bible Society, 2007 - 2016
18   *
19   */
20  package org.crosswire.common.util;
21  
22  /**
23   * A TimeGate when entered will cause the gate to be closed for a specified
24   * period of time.
25   * 
26   * @see gnu.lgpl.License The GNU Lesser General Public License for details.
27   * @author DM Smith
28   */
29  public class TimeGate {
30      /**
31       * Build a TimeGate that will allow entry no more often than count
32       * milliseconds
33       * 
34       * @param count
35       *            the length of time to keep the gate shut after opening it.
36       */
37      public TimeGate(int count) {
38          closeTime = count;
39      }
40  
41      /**
42       * Determine whether entry through the gate is allowed. Opening the gate
43       * will close it until the TimeGate's interval has passed.
44       * 
45       * @return true if one may enter.
46       */
47      public synchronized boolean open() {
48          // check to see if the gate has been closed long enough.
49          // If so, then open it and note the time that it was opened.
50          long now = System.currentTimeMillis();
51          if (now - then > closeTime) {
52              then = now;
53              return true;
54          }
55  
56          // Otherwise the gate was opened not that long ago and
57          // is still closed.
58          return false;
59      }
60  
61      /**
62       * The interval during which the gate is closed.
63       */
64      private int closeTime;
65  
66      /**
67       * The time in milliseconds that the gate last closed.
68       */
69      private long then;
70  }
71