SQLiteQueue is a basic implementation of job queue for an SQLite connection. It provides multi-threaded or GUI application with asynchronous execution of database tasks in a single separate thread with a single {@link SQLiteConnection}.
The queue is started and stopped using {@link #start} and {@link #stop} methods correspondingly.Each database task is represented by a subclass of {@link SQLiteJob}. A task is scheduled for execution by {@link #execute} method. Tasks are served on first-come, first-serve basis.
Public methods of SQLiteQueue are
thread-safe, unless noted otherwise. When writing tasks, it's a good practice to keep transaction boundaries within single task. That is, if you BEGIN TRANSACTION in the task, make sure you COMMIT or ROLLBACK in the end. Otherwise, your transaction will remain unfinished, locks held, and you possible wouldn't know which job will execute next in the context of this unfinished transaction.
SQLiteQueue may be subclassed in order to change certain behavior. If you need some things to be done differently, look for a protected method to override. For example, you can implement a priority queue instead of FIFO queue.
SQLiteQueue and SQLiteJob are written to handle exceptions and errors in a controlled way. In particular, if the queue thread terminates abnormally, SQLiteQueue will try to "reincarnate" by starting another thread and opening another connection to the database. All queued tasks (except for the one that caused the problem) should survive the reincarnation and execute in the new thread.
Reincarnation is not possible for in-memory database, since the database is lost after connection closes.
Some examples:
void start() { myQueue = new SQLiteQueue(myDatabaseFile); myQueue.start(); } int getTableRowCount(final String tableName) { return myQueue.execute(new SQLiteJob<Integer>() { protected Integer job(SQLiteConnection connection) throws SQLiteException { SQLiteStatement st = connection.prepare("SELECT COUNT(*) FROM " + tableName); try { st.step(); return st.columnInt(0); } finally { st.dispose(); } } }).complete(); }
@author Igor Sereda
@see SQLiteJob