Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ID generator for the Objects created

I need a class which creates Objects assigning an ID to each Object created. This ID is as usual an int attribute to the class. I want this value (ID) to be increased each time an Object is created and then to be assigned to that Object starting with 1. It strikes me that I need a static int attribute.

How can I initialize this static attribute?

Should I create a separate method to do the increment of the ID (as an ID generator) which is invoked inside the constructor?

What is in general the most effective and well-designed manner to implement that?

like image 378
arjacsoh Avatar asked Oct 05 '11 11:10

arjacsoh


3 Answers

You could also try java.util.concurrent.AtomicInteger, which generates IDs in

  1. a atomic way and
  2. sequential

You may use this in a static context like:

private static final AtomicInteger sequence = new AtomicInteger();
private SequenceGenerator() {}

public static int next() {
    return sequence.incrementAndGet();
}
like image 132
Andreas Avatar answered Nov 03 '22 03:11

Andreas


Just like you mention use a static int for the id, and increment it when creating new objects.

class MyObject {

    private static int counter = 0;

    public final int objectId;

    MyObject() {
        this.objectId = counter++;
    }
}

Please note that you need to protect counter++ if MyObject is created by multiple threads (for example using AtomicInteger as the other answers suggest).

like image 25
dacwe Avatar answered Nov 03 '22 04:11

dacwe


I would suggest to use AtomicInteger, which is thread-safe

class MyObject
{
    private static AtomicInteger uniqueId=new AtomicInteger();
    private int id;

    MyObject()
    {
       id=uniqueId.getAndIncrement();
    }

}
like image 5
Barmaley Avatar answered Nov 03 '22 02:11

Barmaley