Never been to DZone Snippets before?

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

IdGenerator in java (See related posts)

// IdGenerator

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

} // IdGenerator

Comments on this post

Maj0r posts on Feb 14, 2007 at 04:22
#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.


t_madhav posts on Feb 14, 2007 at 09:08
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.
Maj0r posts on Feb 14, 2007 at 09:36
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.

You need to create an account or log in to post comments to this site.


Click here to browse all 4863 code snippets

Related Posts