Created
October 5, 2021 06:45
-
-
Save Koboo/1e0f13125ceb3a147a7b8214e0f47c1c to your computer and use it in GitHub Desktop.
Simple utility class to automatically generate long ids
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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