Skip to content

Instantly share code, notes, and snippets.

@Koboo
Created October 5, 2021 06:45
Show Gist options
  • Save Koboo/1e0f13125ceb3a147a7b8214e0f47c1c to your computer and use it in GitHub Desktop.
Save Koboo/1e0f13125ceb3a147a7b8214e0f47c1c to your computer and use it in GitHub Desktop.
Simple utility class to automatically generate long ids
import java.util.concurrent.atomic.AtomicLong;
import java.util.function.Predicate;
public class LongId {
private final AtomicLong atomicLong = new AtomicLong(0);
public long generateId(Predicate<Long> exists) {
if(this.atomicLong.get() == Integer.MAX_VALUE) {
this.atomicLong.set(0);
}
long id = this.atomicLong.incrementAndGet();
if(exists.test(id)) {
id = generateId(exists);
}
return id;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment