• Post Reply Bookmark Topic Watch Topic
  • New Topic

Creating Unique ID in Servlet

 
Pawan Kumar
Greenhorn
Posts: 23
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hello.
I want a Unique id to be produced in servlet.when user connect to the servlet by submiting a form.at presetnt i am useing this code.a simple one
synchronized public String generateUniqId()
{return (new Long(UniqId).toString());
}
but it is not woring .
pawan
 
Carl Trusiak
Sheriff
Posts: 3341
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
This isn't a straight forward as it first appears. You need to ensure it's Unique for multiple instances of your servlet and in the case of most Servlet runners, for Multiple JVM's. To do so using a class variable, you need to see how the servlet runner maintains visability accross JVMs. Also, you need to concider the possiblity of running your application accross multiple Computers (As is happening more often with bigger ecommerce sites) If you have a database, the best solution is to obtain a unique ID from it. You can use a Table and obtain the lock, increment the ID then release the lock. This approach works for multiple JVM's and Multiple Machines. Another approach is to have the information in a RandomAssess file, use a syncronized method to read in the last number, increment it and write it back out. This will work across Multiple JVM's that are unaware of each other. Both of these methods will ensure the Number is unique even after a restart of the server. The quickest way is to write a class that has a class variable (static variable) and has a sycronized method to increment it and return the result. Here is where a concept called NameSpace comes into the picture. On most servlet runners today, if the class is loaded from the servlet runners classpath, then all copies of the JVM share the one variable. If it is in your servers classpath then each JVM get's it's own copy. If it loaded from the current directory ie WEB-INF/classes, each class loader gets it's own copy. Therefore, compile the class jar it and put it in the servlet runners classpath.
------------------
Hope This Helps
Carl Trusiak
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!