KickJava   Java API By Example, From Geeks To Geeks.

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


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

3 package jodd.util.idgen;
4
5 /**
6  * Simple synchronized sequence id generator. It generates long numbers in a
7  * sequence. When counter reaches max long, it will be set back to zero.
8  */

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

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

27     public SimpleLongIdGenerator(long initialValue) {
28         this(initialValue, Long.MAX_VALUE, true);
29     }
30
31     /**
32      * Creates a new cycled id generator with specified range.
33      */

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

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

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