webrtc_m130/sdk/android/src/java/org/webrtc/RefCountDelegate.java
Niels Möller f03b365875 Reland "Raise IllegalStateException for calls to retain() or release() on zero ref count"
This is a reland of 8a959bfa88b08e215baf3b38e914c41e483c9ece

Original change's description:
> Raise IllegalStateException for calls to retain() or release() on zero ref count
> 
> Bug: None
> Change-Id: I3205e77b5adfdc4f5dbd7509d1ca0e8b08af62f2
> Reviewed-on: https://webrtc-review.googlesource.com/c/src/+/142175
> Commit-Queue: Niels Moller <nisse@webrtc.org>
> Reviewed-by: Sami Kalliomäki <sakal@webrtc.org>
> Cr-Commit-Position: refs/heads/master@{#28319}

Bug: None
Change-Id: If8fb02ca149257dd29b0c3352347369168a5cef3
Reviewed-on: https://webrtc-review.googlesource.com/c/src/+/142807
Reviewed-by: Magnus Jedvert <magjed@webrtc.org>
Commit-Queue: Niels Moller <nisse@webrtc.org>
Cr-Commit-Position: refs/heads/master@{#28372}
2019-06-25 14:42:55 +00:00

49 lines
1.5 KiB
Java

/*
* Copyright 2018 The WebRTC project authors. All Rights Reserved.
*
* Use of this source code is governed by a BSD-style license
* that can be found in the LICENSE file in the root of the source
* tree. An additional intellectual property rights grant can be found
* in the file PATENTS. All contributing project authors may
* be found in the AUTHORS file in the root of the source tree.
*/
package org.webrtc;
import android.support.annotation.Nullable;
import java.util.concurrent.atomic.AtomicInteger;
/**
* Implementation of RefCounted that executes a Runnable once the ref count reaches zero.
*/
class RefCountDelegate implements RefCounted {
private final AtomicInteger refCount = new AtomicInteger(1);
private final @Nullable Runnable releaseCallback;
/**
* @param releaseCallback Callback that will be executed once the ref count reaches zero.
*/
public RefCountDelegate(@Nullable Runnable releaseCallback) {
this.releaseCallback = releaseCallback;
}
@Override
public void retain() {
int updated_count = refCount.incrementAndGet();
if (updated_count < 2) {
throw new IllegalStateException("retain() called on an object with refcount < 1");
}
}
@Override
public void release() {
int updated_count = refCount.decrementAndGet();
if (updated_count < 0) {
throw new IllegalStateException("release() called on an object with refcount < 1");
}
if (updated_count == 0 && releaseCallback != null) {
releaseCallback.run();
}
}
}