1/*
2 * Copyright (C) 2007 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 android.database.sqlite;
18
19import android.database.CursorWindow;
20
21/**
22 * An object created from a SQLiteDatabase that can be closed.
23 */
24public abstract class SQLiteClosable {
25    private int mReferenceCount = 1;
26
27    protected abstract void onAllReferencesReleased();
28    protected void onAllReferencesReleasedFromContainer() {}
29
30    public void acquireReference() {
31        synchronized(this) {
32            if (mReferenceCount <= 0) {
33                throw new IllegalStateException(
34                        "attempt to re-open an already-closed object: " + getObjInfo());
35            }
36            mReferenceCount++;
37        }
38    }
39
40    public void releaseReference() {
41        boolean refCountIsZero = false;
42        synchronized(this) {
43            refCountIsZero = --mReferenceCount == 0;
44        }
45        if (refCountIsZero) {
46            onAllReferencesReleased();
47        }
48    }
49
50    public void releaseReferenceFromContainer() {
51        boolean refCountIsZero = false;
52        synchronized(this) {
53            refCountIsZero = --mReferenceCount == 0;
54        }
55        if (refCountIsZero) {
56            onAllReferencesReleasedFromContainer();
57        }
58    }
59
60    private String getObjInfo() {
61        StringBuilder buff = new StringBuilder();
62        buff.append(this.getClass().getName());
63        buff.append(" (");
64        if (this instanceof SQLiteDatabase) {
65            buff.append("database = ");
66            buff.append(((SQLiteDatabase)this).getPath());
67        } else if (this instanceof SQLiteProgram) {
68            buff.append("mSql = ");
69            buff.append(((SQLiteProgram)this).mSql);
70        } else if (this instanceof CursorWindow) {
71            buff.append("mStartPos = ");
72            buff.append(((CursorWindow)this).getStartPosition());
73        }
74        buff.append(") ");
75        return buff.toString();
76    }
77}
78