DulcetAirman icon

Instance Counting

DulcetAirman | PRO | 05/11/19 07:20:58 PM UTC | 0 ⭐ | 595 👁️ | Never ⏰ | []
Java |

1.27 KB

|

None

|

0 👍

/

0 👎

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
  }
}

Comments