1 // Copyright (c) 2016, Facebook, Inc. All rights reserved.
2 // This source code is licensed under the BSD-style license found in the
3 // LICENSE file in the root directory of this source tree. An additional grant
4 // of patent rights can be found in the PATENTS file in the same directory.
8 import java
.util
.concurrent
.atomic
.AtomicBoolean
;
11 * Offers functionality for implementations of
12 * {@link AbstractNativeReference} which have an immutable reference to the
13 * underlying native C++ object
15 public abstract class AbstractImmutableNativeReference
16 extends AbstractNativeReference
{
19 * A flag indicating whether the current {@code AbstractNativeReference} is
20 * responsible to free the underlying C++ object
22 private final AtomicBoolean owningHandle_
;
24 protected AbstractImmutableNativeReference(final boolean owningHandle
) {
25 this.owningHandle_
= new AtomicBoolean(owningHandle
);
29 public boolean isOwningHandle() {
30 return owningHandle_
.get();
34 * Releases this {@code AbstractNativeReference} from the responsibility of
35 * freeing the underlying native C++ object
37 * This will prevent the object from attempting to delete the underlying
38 * native object in its finalizer. This must be used when another object
39 * takes over ownership of the native object or both will attempt to delete
40 * the underlying object when garbage collected.
42 * When {@code disOwnNativeHandle()} is called, {@code dispose()} will
43 * subsequently take no action. As a result, incorrect use of this function
44 * may cause a memory leak.
49 protected final void disOwnNativeHandle() {
50 owningHandle_
.set(false);
55 if (owningHandle_
.compareAndSet(true, false)) {
61 * The helper function of {@link AbstractImmutableNativeReference#dispose()}
62 * which all subclasses of {@code AbstractImmutableNativeReference} must
63 * implement to release their underlying native C++ objects.
65 protected abstract void disposeInternal();