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