KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > jodd > util > idgen > SimpleIdGenerator


1 // Copyright (c) 2003-2007, Jodd Team (jodd.sf.net). All Rights Reserved.
2

3 package jodd.util.idgen;
4
5 /**
6  * Simple synchronized int ids sequence generator. It takes the positive sequnce range (boundaries are included).
7  * Optionally, it supports cycling, when counter reaches the max value. Otherwise an exception is thrown.
8  * @see SimpleLongIdGenerator
9  */

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     /**
19      * Creates a new default cycled id generator. Starts from 1 and counts up to max int value.
20      */

21     public SimpleIdGenerator() {
22         this(1, Integer.MAX_VALUE, true);
23     }
24
25     /**
26      * Creates a new cycled id generator with specified initial value.
27      */

28     public SimpleIdGenerator(int initialValue) {
29         this(initialValue, Integer.MAX_VALUE, true);
30     }
31
32     /**
33      * Creates a new cycled id generator with specified range.
34      */

35     public SimpleIdGenerator(int initialValue, int maxValue) {
36         this(initialValue, maxValue, true);
37     }
38
39     /**
40      * Creates a new id generator with specified range and cycling flag.
41      */

42     public SimpleIdGenerator(int initialValue, int maxValue, boolean cycle) {
43         if (initialValue < 0) {
44             throw new IllegalArgumentException JavaDoc("Initial value '" + initialValue + "' must be a positive number.");
45         }
46         if (maxValue <= initialValue) {
47             throw new IllegalArgumentException JavaDoc("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     /**
55      * Returns the next value from the sequence. Thread-safe.
56      */

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 JavaDoc("Max value already reached.");
64             }
65             value = initialValue;
66         }
67         return id;
68     }
69 }
70
Popular Tags