Advertisement
DulcetAirman

Instance Counting

May 11th, 2019
221
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.27 KB | None | 0 0
  1. package ch.claude_martin;
  2.  
  3. import java.util.function.LongConsumer;
  4.  
  5. public final class SomeClass {
  6.   /**
  7.    * The number of instances of this class.
  8.    */
  9.   private static long instanceCount = 0L;
  10.   { // nonstatic initialisation block
  11.     synchronized (SomeClass.class) {
  12.       SomeClass.instanceCount++;
  13.     }
  14.   }
  15.  
  16.   /**
  17.    * Returns the number of instances of {@link SomeClass}.
  18.    */
  19.   public static long getInstanceCount() {
  20.     synchronized (SomeClass.class) {
  21.       return SomeClass.instanceCount;
  22.     }
  23.   }
  24.  
  25.   /**
  26.    * Applies the number of instances to the given action.
  27.    *
  28.    * @param action
  29.    *          The action that reads the number of instances. All construction of
  30.    *          new objects is blocked until this action is finished.
  31.    */
  32.   public static void acceptInstanceCount(LongConsumer action) {
  33.     synchronized (SomeClass.class) {
  34.       action.accept(SomeClass.instanceCount);
  35.     }
  36.   }
  37.  
  38.   public static void main(String[] args) throws InterruptedException {
  39.     System.out.println(getInstanceCount());// 0
  40.     new SomeClass();
  41.     acceptInstanceCount(System.out::println);// 1
  42.     Thread thread = new Thread(SomeClass::new);
  43.     thread.start();
  44.     thread.join();
  45.     acceptInstanceCount(System.out::println);// 2
  46.   }
  47. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement