I have to generate a unique number in Java (for my machine on which the code is running) so that in C++ it can correspond to uint32_t
. In general other C++ program should be able to read this unique number properly as uint32_t
. I am sending this info in a byte array which other C++ program is deserializing it to get this number. I cannot change the datatype for this number in C++ program as of now.
private static final AtomicInteger clientId = new AtomicInteger(0);
// will be called many time when the program is running after initialization
public static int getClientId() {
int counter = clientId.incrementAndGet();
return counter == Integer.MAX_VALUE ? 0 : counter;
}
// called only once at startup
public static void setClientId(final int counter) {
clientId.addAndGet(counter == Integer.MAX_VALUE ? 0 : counter);
}
So I came up with above code. My setClientId
method will be called only once during the application startup (initialization phase):
- If this machine is running code for the first time, like it's a new machine then I will pass
0
tosetClientId
method. - If this machine was running code already but we restarted the server, then I will look up in a database what was the last saved value for this machine (as we are also saving this value in db every few minutes) and then I will pass that value to
setClientId
method.
And then later on when my program is running (after the initialization) it will keep calling getClientId
method to give me the actual unique clientId.
Is this the right way of generating unique id for my machine which will be uint32_t
for the C++ program? I am also making sure that if the value reaches Integer.MAX_VALUE
then set it to 0 and start again. Do I have to do this? Or I can take negative values as well for this uint32_t
?
Basically, I want to generate a unique number for my machine that should always corresonds to uint32_t
. If machine is a new machine, we can start with number 0 (bcoz when we look up the value for this machine the db, there won't be any value so we will start with 0) but if machine has already ran this code before, then start with what was the last saved value in the database.