RefCountBase.java revision cc6139467c1c9545de1f098d938409e182c9b7ad
1/*
2 * Copyright (C) 2014 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 *      http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17package com.android.camera.async;
18
19import com.google.common.annotations.VisibleForTesting;
20import com.google.common.base.Preconditions;
21
22/**
23 * Wraps an object with reference counting. When the reference count goes to 0
24 * for the first time, the object is closed.
25 */
26public class RefCountBase<T extends SafeCloseable> implements SafeCloseable {
27    private final Object mLock;
28    private final T mObject;
29    private int mRefCount;
30    private boolean mObjectClosed;
31
32    public RefCountBase(T object) {
33        this(object, 1);
34    }
35
36    public RefCountBase(T object, int initialReferenceCount) {
37        Preconditions.checkState(
38                initialReferenceCount > 0, "initialReferenceCount is not greater than 0.");
39        mLock = new Object();
40        mObject = object;
41        mRefCount = initialReferenceCount;
42        mObjectClosed = false;
43    }
44
45    public void addRef() {
46        synchronized (mLock) {
47            Preconditions.checkState(!mObjectClosed,
48                    "addRef on an object which has been closed.");
49            mRefCount++;
50        }
51    }
52
53    public T get() {
54        return mObject;
55    }
56
57    @Override
58    public void close() {
59        synchronized (mLock) {
60            // A SafeCloseable must tolerate multiple calls to close().
61            if (mObjectClosed) {
62                return;
63            }
64            mRefCount--;
65            if (mRefCount > 0) {
66                return;
67            }
68            mObjectClosed = true;
69        }
70        // Do this outside of the mLock critical section for speed and to avoid
71        // deadlock.
72        mObject.close();
73    }
74
75    @VisibleForTesting
76    public int getRefCount() {
77        synchronized (mLock) {
78            return mRefCount;
79        }
80    }
81}
82