Created
May 13, 2016 13:05
-
-
Save Sythelux/846f4474e3d0aa170e3c54401061eff6 to your computer and use it in GitHub Desktop.
Little ID Generator, that makes ids reusable after freeing
This file contains hidden or 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
public class ReusableIDGenerator { | |
private static Map<Integer, Boolean> map = Collections.synchronizedMap(new HashMap<Integer, Boolean>()); | |
private ReusableIDGenerator() {} | |
public static int get() { | |
for (int i = 0; i < Integer.MAX_VALUE; i++) { | |
if (map.containsKey(i)) { | |
if (!map.get(i)) { | |
map.put(i, true); | |
return i; | |
} | |
} else { | |
map.put(i, true); | |
return i; | |
} | |
} | |
return -1; | |
} | |
public static void free(int i) { | |
map.put(i, false); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment