Home IT Linux Windows Database Network Programming Server Mobile  
  Home \ Programming \ Explore Android SQLite3 multithreading     - A process of how to get the current traffic in GNU Linux (Linux)

- Spark local development environment to build (Server)

- Lua4.0 interpreter entrance (Programming)

- To install the latest version of the EPEL on CentOS 5.x or 6.x (Linux)

- SteamOS installation under Ubuntu 14.04 (Linux)

- Linux operating system set up to effectively prevent ARP attacks (Linux)

- CentOS / Linux SWAP partitions added (Linux)

- Enterprise-class GitHub warehousing environment build (Server)

- C ++ class implementation date operator overloading (Programming)

- How to disable IPv6 on Ubuntu, Linux Mint, Debian (Linux)

- Ubuntu 14.10 installation SecureCRT 7.3 (Linux)

- Top 10: HTML5, JavaScript 3D game engine and framework (Linux)

- How to track performance issues when using the Unity Game Development Android (Programming)

- Ubuntu install ruby (Linux)

- Verify the character set on MyCAT (Database)

- To install Google Chrome browser under Ubuntu 14.04 LTS (Linux)

- Achieve camera preview by ffplay (Linux)

- Partition contrast manifestations under Windows and Linux (Linux)

- Ubuntu / openSUSE users to install Veusz 1.21.1 (Linux)

- Root of AVL Tree- achieve balanced search trees AVL tree (Programming)

  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,
- linux firewall configuration (Linux)
- Analysis of potential problems through custom Orabbix monitoring Oracle (Database)
- Oracle 11g new features of the collection of multi-column statistics (Database)
- Samba file sharing server set up (Server)
- Nginx supports user multi-threaded downloads and resume broken (Server)
- How to enable curl command HTTP2 support (Linux)
- Java multithreading easy to confuse the concept (Programming)
- Oracle 12c In-Memory Study (Database)
- Ubuntu 14.04 LTS compiler installation R Source Code (Linux)
- CentOS yum source as the default setting methods in DVD (Linux)
- Linux shell script to adjust the Task Scheduler (Linux)
- Linux Apache server security (Linux)
- iOS Sensor Development - add to APP phone password, fingerprint security authentication (Programming)
- Learning MySQL data types (Database)
- Java Generics Introduction --HashMap summary (Programming)
- Will Laravel become the most successful PHP framework? (Programming)
- Monitor traffic Linux Shell Edition (Programming)
- Save the database data files into Oracle Learning (Database)
- Use Ganglia to monitor your cluster (Server)
- C language - Traverse pci device (Programming)
  CopyRight 2002-2016 newfreesoft.com, All Rights Reserved.