Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- package ch.claude_martin;
- import java.util.function.LongConsumer;
- public final class SomeClass {
- /**
- * The number of instances of this class.
- */
- private static long instanceCount = 0L;
- { // nonstatic initialisation block
- synchronized (SomeClass.class) {
- SomeClass.instanceCount++;
- }
- }
- /**
- * Returns the number of instances of {@link SomeClass}.
- */
- public static long getInstanceCount() {
- synchronized (SomeClass.class) {
- return SomeClass.instanceCount;
- }
- }
- /**
- * Applies the number of instances to the given action.
- *
- * @param action
- * The action that reads the number of instances. All construction of
- * new objects is blocked until this action is finished.
- */
- public static void acceptInstanceCount(LongConsumer action) {
- synchronized (SomeClass.class) {
- action.accept(SomeClass.instanceCount);
- }
- }
- public static void main(String[] args) throws InterruptedException {
- System.out.println(getInstanceCount());// 0
- new SomeClass();
- acceptInstanceCount(System.out::println);// 1
- Thread thread = new Thread(SomeClass::new);
- thread.start();
- thread.join();
- acceptInstanceCount(System.out::println);// 2
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement