1 // Copyright 2023 The Chromium Authors 2 // Use of this source code is governed by a BSD-style license that can be 3 // found in the LICENSE file. 4 5 package org.chromium.net.impl; 6 7 import java.util.concurrent.atomic.AtomicInteger; 8 9 /** 10 * A thread-safe counter that starts at 1 and executes a callback once it 11 * reaches its final value of zero. 12 */ 13 public final class RefCountDelegate { 14 private final AtomicInteger mCount = new AtomicInteger(1); 15 private final Runnable mDelegate; 16 RefCountDelegate(Runnable delegate)17 public RefCountDelegate(Runnable delegate) { 18 mDelegate = delegate; 19 } 20 increment()21 public void increment() { 22 int updated_count = mCount.incrementAndGet(); 23 assert updated_count > 1 : "increment() called on a RefCountDelegate with count < 1"; 24 } 25 decrement()26 public void decrement() { 27 int updated_count = mCount.decrementAndGet(); 28 assert updated_count >= 0 : "decrement() called on a RefCountDelegate with count < 1"; 29 if (updated_count == 0) { 30 mDelegate.run(); 31 } 32 } 33 } 34