Skip to content

Instantly share code, notes, and snippets.

@c-rainstorm
Last active July 30, 2018 12:40
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save c-rainstorm/4e9feee140fa3455c4b2f21f58fc1e4c to your computer and use it in GitHub Desktop.
Save c-rainstorm/4e9feee140fa3455c4b2f21f58fc1e4c to your computer and use it in GitHub Desktop.
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