1 3 package jodd.util.idgen; 4 5 9 public class SimpleLongIdGenerator { 10 11 protected volatile long value; 12 13 protected long initialValue; 14 protected long maxValue; 15 protected boolean cycle; 16 17 20 public SimpleLongIdGenerator() { 21 this(1, Long.MAX_VALUE, true); 22 } 23 24 27 public SimpleLongIdGenerator(long initialValue) { 28 this(initialValue, Long.MAX_VALUE, true); 29 } 30 31 34 public SimpleLongIdGenerator(long initialValue, long maxValue) { 35 this(initialValue, maxValue, true); 36 } 37 38 41 public SimpleLongIdGenerator(long initialValue, long maxValue, boolean cycle) { 42 if (initialValue < 0) { 43 throw new IllegalArgumentException ("Initial value '" + initialValue + "' must be a positive number."); 44 } 45 if (maxValue <= initialValue) { 46 throw new IllegalArgumentException ("Max value '" + maxValue + "' is less or equals to initial value '" + initialValue + "'."); 47 } 48 this.initialValue = this.value = initialValue; 49 this.maxValue = maxValue; 50 this.cycle = cycle; 51 } 52 53 56 public synchronized long next() { 57 long id = value; 58 59 value++; 60 if ((value > maxValue) || (value < 0)) { 61 if (cycle == false) { 62 throw new IllegalStateException ("Max value already reached."); 63 } 64 value = initialValue; 65 } 66 return id; 67 } 68 } 69 | Popular Tags |