001    package org.hackystat.utilities.tstamp;
002    
003    import java.util.HashSet;
004    import java.util.Set;
005    
006    /**
007     * Provides a way to guarantee unique timestamps by keeping track of the old ones and incrementing
008     * the millisecond field as needed to create a unique one. The behavior of this class is to 
009     * return the passed tstamp if it is not already in the set, or else return an incremented
010     * version of the tstamp which is incremented enough times to be unique. 
011     * 
012     * @author Philip Johnson
013     */
014    public class TstampSet {
015      
016      /** Holds all of the tstamps previously passed to this set. */
017      private final Set<Long> tstampSet;
018      
019      /**
020       * Create a new TstampSet, which is initialized with no knowledge of prior timestamps.
021       */
022      public TstampSet() {
023        tstampSet = new HashSet<Long>();
024      }
025      
026      /**
027       * Return a new unique timestamp based upon the passed timestamp.  If the passed timestamp does
028       * not exist in the timestamp set, then it is returned (and it is added to the set).  If
029       * the passed timestamp already exists in the set, then it is repeatedly incremented until a
030       * value is obtained that did not already exist in the timestamp set.  This value is then 
031       * returned (and added to the set.)
032       * 
033       * @param tstamp The tstamp to be used as a basis for finding a unique timestamp.
034       * @return A timestamp that did not previously exist in this TstampSet. 
035       */
036      public long getUniqueTstamp(long tstamp) {
037        long currTstamp = tstamp;
038        while (tstampSet.contains(currTstamp)) {
039          currTstamp++;
040        }
041        tstampSet.add(currTstamp);
042        return currTstamp;
043      }
044    }