Search code examples
javauniqueidentifierreusabilityfinalize

Java: How to give unique ids and reuse them?


I am implementing a simple class for giving ids to certain objects like this:

class idObject
{
  private static long next=0;
  private long id;

  idObject()
  {
     id=next;
     next = next +1;
  }

}

and derive all classes that I need my ids from this. The programm runs very long and a lot of objects are created. Thus, i am afraid next can overfow. Which results in non-unique ids. Some of the objects live very long, but most of them are deleted at some point. However, I would like to keep the ids unique.

My question is, is there an easy way, to reuse ids of the objects that are deleted? My idea was to create a list of free ids and add the id of an object when it dies. Originally, i am a C++ programmer, so I thought of using a destructer, which is obviously not available in Java. Is the finalize() method the correct choice in this situation?

Best Regards


Solution

  • If you're worried about running out of IDs, you can use UUIDs. There are 16^32 possible combinations of UUIDs and are randomly generated. If you want to be absolutely sure you don't have a collision with an existing ID, you can always keep a registry of created ones and make sure it doesn't already exist.