SQLiteClosable.java revision c3849200fa60b22ea583ba2a6f902d6a632a5e7e
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    private Object mLock = new Object();
27
28    protected abstract void onAllReferencesReleased();
29    protected void onAllReferencesReleasedFromContainer() {}
30
31    public void acquireReference() {
32        synchronized(mLock) {
33            if (mReferenceCount <= 0) {
34                throw new IllegalStateException(
35                        "attempt to re-open an already-closed object: " + getObjInfo());
36            }
37            mReferenceCount++;
38        }
39    }
40
41    public void releaseReference() {
42        synchronized(mLock) {
43            mReferenceCount--;
44            if (mReferenceCount == 0) {
45                onAllReferencesReleased();
46            }
47        }
48    }
49
50    public void releaseReferenceFromContainer() {
51        synchronized(mLock) {
52            mReferenceCount--;
53            if (mReferenceCount == 0) {
54                onAllReferencesReleasedFromContainer();
55            }
56        }
57    }
58
59    private String getObjInfo() {
60        StringBuilder buff = new StringBuilder();
61        buff.append(this.getClass().getName());
62        buff.append(" (");
63        if (this instanceof SQLiteDatabase) {
64            buff.append("database = ");
65            buff.append(((SQLiteDatabase)this).getPath());
66        } else if (this instanceof SQLiteProgram || this instanceof SQLiteStatement ||
67                this instanceof SQLiteQuery) {
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