Last active
July 30, 2018 12:40
-
-
Save c-rainstorm/4e9feee140fa3455c4b2f21f58fc1e4c to your computer and use it in GitHub Desktop.
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 Emperor { | |
private Emperor() { | |
} | |
private static List<Emperor> emperors; | |
private static final Integer MAX_NUM_OF_EMPEROR = Integer.valueOf(3); | |
private static AtomicInteger lastUsed = new AtomicInteger(-1); | |
static { | |
emperors = new ArrayList<>(); | |
for (int i = 0; i < MAX_NUM_OF_EMPEROR; ++i) { | |
emperors.add(new Emperor()); | |
} | |
} | |
//todo 不显式加锁,如何实现对 emperors 集合中元素的轮询访问 | |
public static Emperor getInstance() { | |
// lastUsed 增加到 Integer.MAX_VALUE 之后的行为和预期不符 | |
Integer index = lastUsed.incrementAndGet(); | |
return emperors.get(index % MAX_NUM_OF_EMPEROR); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment