Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- Limit the number of DIRECT Instances of a class
- class Parent
- {
- .............
- .........
- ..............
- }
- class Child1 extends Parent
- {
- .............
- .........
- ..............
- }
- class Child2 extends Parent
- {
- .............
- .........
- ..............
- }
- static final AtomicInteger count = new AtomicInteger();
- // in your Parent constructor.
- if (getClass() == Parent.class && count.incrementAndGet() >= LIMIT)
- throw new IllegalStateException();
- public class Parent {
- public Parent() {
- if (count.incrementAndGet() >= LIMIT) { //count is an AtomicInt/Long
- throw new InstantiationException("Too many instances");
- }
- protected Parent(boolean placeholder) { //protected means only subclasses can call it
- //do nothing with the placeholder, but it differentiates the two constructors
- }
- }
Add Comment
Please, Sign In to add comment