KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > sync4j > framework > tools > Int16IdGenerator


1 /**
2  * Copyright (C) 2003-2005 Funambol
3  *
4  * This program is free software; you can redistribute it and/or modify
5  * it under the terms of the GNU General Public License as published by
6  * the Free Software Foundation; either version 2 of the License, or
7  * (at your option) any later version.
8  *
9  * This program is distributed in the hope that it will be useful,
10  * but WITHOUT ANY WARRANTY; without even the implied warranty of
11  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12  * GNU General Public License for more details.
13  *
14  * You should have received a copy of the GNU General Public License
15  * along with this program; if not, write to the Free Software
16  * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
17  */

18
19 package sync4j.framework.tools;
20
21 import sync4j.framework.tools.IdGenerator;
22
23 /**
24  * This class implements an ID generator, that increments the counter each time
25  * the next method is called. When the maximum 16 bit integer si reached, it
26  * starts again from 1. The first retuned number is 1.
27  * <p>
28  * SimpleIdGenerator is thread-safe
29  *
30  * @author Stefano Fornari @ funambol
31  */

32 public final class Int16IdGenerator implements IdGenerator, java.io.Serializable JavaDoc {
33
34     // -------------------------------------------------------------- Properties
35

36     /**
37      * The counter
38      */

39     private int counter;
40
41     public int getCounter() {
42         return counter;
43     }
44
45     // ------------------------------------------------------------ Constructors
46

47     /**
48      * Creates a new instance of SimpleIdGenerator
49      *
50      * @param counter the starting value
51      * @param increment the increment
52      */

53     public Int16IdGenerator() {
54         counter = 0;
55     }
56
57     /**
58      * Reset the generator to 0.
59      */

60     public void reset() {
61         counter = 0;
62     }
63
64     /**
65      * Returns the next value of the counter (incrementing the counter by the
66      * increment)
67      *
68      * @return the next generated value
69      */

70     public synchronized String JavaDoc next() {
71         if (counter == 0x0000ffff) {
72             reset();
73         }
74
75         return String.valueOf(++counter);
76     }
77
78     /**
79      * Returns the last generated id (which is the current id).
80      *
81      * @return the last generated id
82      */

83     public synchronized String JavaDoc current() {
84         return String.valueOf(counter);
85     }
86 }
Popular Tags