DZone Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world

Snippets has posted 5883 posts at DZone. View Full User Profile

IdGenerator In Java

09.17.2006
| 3792 views |
  • submit to reddit
        // IdGenerator

public class IdGenerator {
	
	private long maxId; 
	
	public IdGenerator(long start) {
		maxId = start;
	}
	
	public long getNextId () {
		return ++maxId;
	}

} // IdGenerator
    

Comments

Torsten Krall replied on Wed, 2007/02/14 - 5:08am

As I wrote: "If one generator supplies the entire application with ids you will have to implement it as singleton. ". There is in fact sometimes the need to supply different entities with unique ids. As I wrote, in THIS situation you will have to use a singleton, otherwise not.

Torsten Krall replied on Wed, 2007/02/14 - 5:08am

#getNextId has to be synchronized to avoid same next-ids. public synchronized long getNextId () { return ++maxId; } If one generator supplies the entire application with ids you will have to implement it as singleton.

Madhav Turangi replied on Wed, 2007/02/14 - 8:33am

Making it synchronized would be useful though it would be impractical making it singleton. In practice there won't be any application which will have only one entity which use IDs. Making it Singleton will restrict the use fo this class to generate IDs for more than one entity in a single application.