Home IT Linux Windows Database Network Programming Server Mobile  
  Home \ Programming \ Explore Android SQLite3 multithreading     - Linux user directory (Linux)

- Linux screen commonly commands (Linux)

- Use Visual Studio to compile and use WinGDB remote debugging embedded Linux programs (Programming)

- Installation and Configuration Tomcat environment CentOS 6.6 (Server)

- PostgreSQL query lock and kill the process (Database)

- Linux simple commands (Linux)

- Server Security Analysis attack on Linux (Linux)

- Python Socket Network Programming (Programming)

- Linux Powerful IDE - Geany configuration instructions (Linux)

- Explore Android SQLite3 multithreading (Programming)

- RedHat Linux 9.0 under P4VP-MX motherboard graphics resolution of problems (Linux)

- Using Linux stat command to view the files (Linux)

- C # dynamic class notes --- (Dynamic) Applications (Programming)

- AngularJS notes --- Data Binding (Programming)

- How to use Android Studio development / debugging Android source code (Linux)

- Java string intern constant pool resolution Introduction (Programming)

- Linux input and output redirection (Linux)

- How to remove the Linux memory Cache, Buffer and swap space (Linux)

- MySQL Data Types (Database)

- The bulk batch multiple rows of data collect (Database)

  Explore Android SQLite3 multithreading
  Add Date : 2018-11-21      
  Recently to do the project in the multi-threaded database read and write when throwing an exception, which is of course I have not understood in place of SQlite3, so after a careful inquiry about it.

On the true role of getWriteableDataBase () and getReadableDatabase ()
GetWriteableDataBase () is the equivalent of getReadableDatabase () is a sub-method, getWriteableDataBase () is a read-only way to open a reference to SQLiteDatabase, if the database is not writeable at this time will throw an exception, such as the database disk Space full of the situation. The default is to getReadableDatabase () call getWriteableDataBase () method, if the database is not written when it will return to a read-only way to open SQLiteDatabase reference, which is the most obvious difference between the two.
The key source is as follows:

Public synchronized SQLiteDatabase getWritableDatabase () {
If (mDatabase! = Null) {
        If (! MDatabase.isOpen ()) {
        // darn! The user closed the database by calling mDatabase.close ()
        MDatabase = null;
        } Else if (! MDatabase.isReadOnly ()) {
        Return mDatabase; // The database is already open for business

Public synchronized SQLiteDatabase getReadableDatabase () {
    If (mDatabase! = Null) {
        If (! MDatabase.isOpen ()) {
        // darn! The user closed the database by calling mDatabase.close ()
        MDatabase = null;
        } Else {
        Return mDatabase; // The database is already open for business
    Try {
        Return getWritableDatabase ();

The synchronization lock for SQLiteDatabase
In fact, when using only a reference to SQLiteDatabase, SQLiteDatabase CRUD operation will be coupled with a lock (because the db file, so accurate to the database level), which ensures that at the same time you can only carry out an operation, whether it is not In the same thread, this leads to the fact that if you use the singleton pattern for SQLiteOpenHelper in your program, any optimizations you make to the database read and write are "futile."

Multi-threaded read the database
Look at the source code You will find in the database operation only add, delete, update will call lock (), and query () is not called, but when loading data, call SQLiteQuery fillWindow method, and the method is still Will call SQLiteDatabase.lock (), so in order to truly multi-threaded read the database, only each thread using their SQLiteOpenHelper object to read, so you can avoid the synchronization lock. The key source is as follows:

/ * Package * / int fillWindow (CursorWindow window,
    Int maxRead, int lastPos) {
    Long timeStart = SystemClock.uptimeMillis ();
    MDatabase.lock ();
    MDatabase.logTimeStat (mSql, timeStart, SQLiteDatabase.GET_LOCK_LOG_PREFIX);
    Try {...

Multi-threaded read and write
The key is to achieve multi-threaded read and write enableWriteAheadLogging attribute, this method API Level 11 added, which is more than 3.0 version of the basic impossible to achieve a true multi-threaded read and write. Simply put, this can be controlled by calling enableWriteAheadLogging () and disableWriteAheadLogging (), which allows a write thread to work with multiple read threads on a single SQLiteDatabase if it is allowed to run multithreaded. Implementation principle is written in a separate log file, the read operation is the original data file, is written before the start of the operation, so as not affect each other. When the write operation after the end of the operation will be aware of the new database state. Of course, the drawbacks of doing so will consume more memory space.

Multi-threaded write
This would not have thought, SQLite do not support, if there is a demand can use multiple database files.

(1) Have you ever thought how many database connections SQLite supports, in fact, the official API documentation (enableWriteAheadLogging () method) gives the most accurate answer: The maximum number of connections used to execute queries in parallel is dependent upon the Device memory and possible other properties. Is to see how much memory you have, but I feel this is a bit big, is not it? Haha.

(2) When you use only a SQLiteDatabase in a multi-threaded reference, you need to pay special attention to your SQLiteDataBase.close () call the time, because you are using the same reference, such as in a thread when a Add operation after the end Immediately shut down the database connection, while another site is ready to perform the query operation, but this time db has been closed, and then will report an exception error. At this point there are generally three solutions, (1) simple and crude to all the CRUD add a synchronized keyword; (2) never close the database connection, only the last exit is to close the connection. In fact, each time the implementation of getWriteableDataBase () or getReadableDatabase () method, if there is a database connection has been established directly return (Exception: If the old connection is read-only open, the new connection is successful, Old connection), so the program will always have and only one database connection (the premise is a single case), resource consumption is very small. (3) can be their own reference count, a simple example code is as follows:

// Open the database method
Public synchronized SQLiteDatabase openDatabase () {
If (mOpenCounter.incrementAndGet () == 1) {
// Opening new database
Try {
MDatabase = sInstance.getWritableDatabase ();
} Catch (Exception e) {
MDatabase = sInstance.getReadableDatabase ();
Return mDatabase;

// Close the database method
Public synchronized void closeDatabase () {
If (mOpenCounter.decrementAndGet () == 0) {
// Closing database
MDatabase.close ();

(3) there are some good habits and common sense, such as closing the Cursor, the use of Transaction, SQLite stored data does not distinguish between types, and SQLite support most standard SQL statements,
- Apache Kafka: the next generation of distributed messaging system (Server)
- ActiveMQ-based shared file system HA solutions (Server)
- Linux how to view your JDK installation (Linux)
- Chkconfig set boot start under Linux (Linux)
- Turning off the interface eth0: error: Disconnect the device 'eth0' (Linux)
- Thinking in Java study notes - everything is an object (Programming)
- CentOS6.5 installation Docker (Linux)
- Linux Thread Synchronization (Programming)
- Oracle () trunc function usage (Database)
- Analysis of native Java keywords (Programming)
- Linux dmidecode command detail (Linux)
- Getting CentOS Learning Notes (Linux)
- Getting Started with Linux system to learn: how to check memory usage of Linux (Linux)
- Installed FFmpeg 2.6.3 on Ubuntu / Debian / Fedora system (Linux)
- Linux System Getting Started Tutorial: Using the Linux common commands (Linux)
- Reason C ++ program running under Linux a segmentation fault core dumped in (Programming)
- Inject script commands manually annotated summary (Linux)
- About enhanced Linux / Unix server system security program (Linux)
- a virtual machine created migrated to host RHEL6.4 on Ubuntu 14.04 (Linux)
- The best known for archiving / compression tool under linux (Linux)
  CopyRight 2002-2016 newfreesoft.com, All Rights Reserved.