Class SQLiteConnectionPool
- java.lang.Object
-
- android.database.sqlite.SQLiteConnectionPool
-
- All Implemented Interfaces:
Closeable,AutoCloseable
public final class SQLiteConnectionPool extends Object implements Closeable
Maintains a pool of active SQLite database connections.At any given time, a connection is either owned by the pool, or it has been acquired by a
SQLiteSession. When theSQLiteSessionis finished with the connection it is using, it must return the connection back to the pool.The pool holds strong references to the connections it owns. However, it only holds weak references to the connections that sessions have acquired from it. Using weak references in the latter case ensures that the connection pool can detect when connections have been improperly abandoned so that it can create new connections to replace them if needed.
The connection pool is thread-safe (but the connections themselves are not).
Exception safety
This code attempts to maintain the invariant that opened connections are always owned. Unfortunately that means it needs to handle exceptions all over to ensure that broken connections get cleaned up. Most operations invokving SQLite can throw
SQLiteExceptionor other runtime exceptions. This is a bit of a pain to deal with because the compiler cannot help us catch missing exception handling code.The general rule for this file: If we are making calls out to
SQLiteConnectionthen we must be prepared to handle any runtime exceptions it might throw at us. Note that out-of-memory is anError, not aRuntimeException. We don't trouble ourselves handling out of memory because it is hard to do anything at all sensible then and most likely the VM is about to crash.
-
-
Field Summary
Fields Modifier and Type Field Description static intCONNECTION_FLAG_INTERACTIVEConnection flag: Connection is being used interactively.static intCONNECTION_FLAG_PRIMARY_CONNECTION_AFFINITYConnection flag: Primary connection affinity.static intCONNECTION_FLAG_READ_ONLYConnection flag: Read-only.
-
Method Summary
All Methods Static Methods Instance Methods Concrete Methods Modifier and Type Method Description SQLiteConnectionacquireConnection(String sql, int connectionFlags, CancellationSignal cancellationSignal)Acquires a connection from the pool.voidclose()Closes the connection pool.voidcollectDbStats(ArrayList<SQLiteDebug.DbStats> dbStatsList)Collects statistics about database connection memory usage.voiddump(Printer printer, boolean verbose)Dumps debugging information about this connection pool.protected voidfinalize()Invoked when the garbage collector has detected that this instance is no longer reachable.static SQLiteConnectionPoolopen(SQLiteDatabaseConfiguration configuration)Opens a connection pool for the specified database.voidreconfigure(SQLiteDatabaseConfiguration configuration)Reconfigures the database configuration of the connection pool and all of its connections.voidreleaseConnection(SQLiteConnection connection)Releases a connection back to the pool.booleanshouldYieldConnection(SQLiteConnection connection, int connectionFlags)Returns true if the session should yield the connection due to contention over available database connections.StringtoString()Returns a string containing a concise, human-readable description of this object.
-
-
-
Field Detail
-
CONNECTION_FLAG_READ_ONLY
public static final int CONNECTION_FLAG_READ_ONLY
Connection flag: Read-only.This flag indicates that the connection will only be used to perform read-only operations.
- See Also:
- Constant Field Values
-
CONNECTION_FLAG_PRIMARY_CONNECTION_AFFINITY
public static final int CONNECTION_FLAG_PRIMARY_CONNECTION_AFFINITY
Connection flag: Primary connection affinity.This flag indicates that the primary connection is required. This flag helps support legacy applications that expect most data modifying operations to be serialized by locking the primary database connection. Setting this flag essentially implements the old "db lock" concept by preventing an operation from being performed until it can obtain exclusive access to the primary connection.
- See Also:
- Constant Field Values
-
CONNECTION_FLAG_INTERACTIVE
public static final int CONNECTION_FLAG_INTERACTIVE
Connection flag: Connection is being used interactively.This flag indicates that the connection is needed by the UI thread. The connection pool can use this flag to elevate the priority of the database connection request.
- See Also:
- Constant Field Values
-
-
Method Detail
-
finalize
protected void finalize() throws ThrowableDescription copied from class:ObjectInvoked when the garbage collector has detected that this instance is no longer reachable. The default implementation does nothing, but this method can be overridden to free resources.Note that objects that override
finalizeare significantly more expensive than objects that don't. Finalizers may be run a long time after the object is no longer reachable, depending on memory pressure, so it's a bad idea to rely on them for cleanup. Note also that finalizers are run on a single VM-wide finalizer thread, so doing blocking work in a finalizer is a bad idea. A finalizer is usually only necessary for a class that has a native peer and needs to call a native method to destroy that peer. Even then, it's better to provide an explicitclosemethod (and implementCloseable), and insist that callers manually dispose of instances. This works well for something like files, but less well for something like aBigIntegerwhere typical calling code would have to deal with lots of temporaries. Unfortunately, code that creates lots of temporaries is the worst kind of code from the point of view of the single finalizer thread.If you must use finalizers, consider at least providing your own
ReferenceQueueand having your own thread process that queue.Unlike constructors, finalizers are not automatically chained. You are responsible for calling
super.finalize()yourself.Uncaught exceptions thrown by finalizers are ignored and do not terminate the finalizer thread. See Effective Java Item 7, "Avoid finalizers" for more.
-
open
public static SQLiteConnectionPool open(SQLiteDatabaseConfiguration configuration)
Opens a connection pool for the specified database.- Parameters:
configuration- The database configuration.- Returns:
- The connection pool.
- Throws:
SQLiteException- if a database error occurs.
-
close
public void close()
Closes the connection pool.When the connection pool is closed, it will refuse all further requests to acquire connections. All connections that are currently available in the pool are closed immediately. Any connections that are still in use will be closed as soon as they are returned to the pool.
- Specified by:
closein interfaceAutoCloseable- Specified by:
closein interfaceCloseable- Throws:
IllegalStateException- if the pool has been closed.
-
reconfigure
public void reconfigure(SQLiteDatabaseConfiguration configuration)
Reconfigures the database configuration of the connection pool and all of its connections.Configuration changes are propagated down to connections immediately if they are available or as soon as they are released. This includes changes that affect the size of the pool.
- Parameters:
configuration- The new configuration.- Throws:
IllegalStateException- if the pool has been closed.
-
acquireConnection
public SQLiteConnection acquireConnection(String sql, int connectionFlags, CancellationSignal cancellationSignal)
Acquires a connection from the pool.The caller must call
releaseConnection(android.database.sqlite.SQLiteConnection)to release the connection back to the pool when it is finished. Failure to do so will result in much unpleasantness.- Parameters:
sql- If not null, try to find a connection that already has the specified SQL statement in its prepared statement cache.connectionFlags- The connection request flags.cancellationSignal- A signal to cancel the operation in progress, or null if none.- Returns:
- The connection that was acquired, never null.
- Throws:
IllegalStateException- if the pool has been closed.SQLiteException- if a database error occurs.OperationCanceledException- if the operation was canceled.
-
releaseConnection
public void releaseConnection(SQLiteConnection connection)
Releases a connection back to the pool.It is ok to call this method after the pool has closed, to release connections that were still in use at the time of closure.
- Parameters:
connection- The connection to release. Must not be null.- Throws:
IllegalStateException- if the connection was not acquired from this pool or if it has already been released.
-
shouldYieldConnection
public boolean shouldYieldConnection(SQLiteConnection connection, int connectionFlags)
Returns true if the session should yield the connection due to contention over available database connections.- Parameters:
connection- The connection owned by the session.connectionFlags- The connection request flags.- Returns:
- True if the session should yield its connection.
- Throws:
IllegalStateException- if the connection was not acquired from this pool or if it has already been released.
-
collectDbStats
public void collectDbStats(ArrayList<SQLiteDebug.DbStats> dbStatsList)
Collects statistics about database connection memory usage.- Parameters:
dbStatsList- The list to populate.
-
dump
public void dump(Printer printer, boolean verbose)
Dumps debugging information about this connection pool.- Parameters:
printer- The printer to receive the dump, not null.verbose- True to dump more verbose information.
-
toString
public String toString()
Description copied from class:ObjectReturns a string containing a concise, human-readable description of this object. Subclasses are encouraged to override this method and provide an implementation that takes into account the object's type and data. The default implementation is equivalent to the following expression:getClass().getName() + '@' + Integer.toHexString(hashCode())
See Writing a useful
toStringmethod if you intend implementing your owntoStringmethod.
-
-