title: Dealing with sqlite 'database is locked' errors in Android
body: <p>I have an application which has times of heavy database activity.  From time to time I used to get SQLite 'database is locked' errors leading to SQLiteExceptions.  Whie I have tried to use:</p>
  
  <pre><code>if((!db.isDbLockedByCurrentThread())&amp;&amp;(!db.isDbLockedByOtherThreads())) {
  </code></pre>
  
  <p>before using save or insert but this hasn't been successful.  So, I have set up the following in a class eg. MyApplication which extends Application like so:</p>
  
  <pre><code>private AtomicBoolean writingToDataBaseFlag = new AtomicBoolean(false);
  </code></pre>
  
  <p>with an accessor:</p>
  
  <pre><code>public AtomicBoolean getWritingToDataBaseFlag() {
      return writingToDataBaseFlag;
  }
  </code></pre>
  
  <p>and any time I want to perform an insert or save I do something like this:</p>
  
  <pre><code>boolean succeeded = false;
  while(!succeeded) {
     if(application.getWritingToDataBaseFlag().compareAndSet(false, true)) {
         if((!db.isDbLockedByCurrentThread())&amp;&amp;(!db.isDbLockedByOtherThreads())) {
             if(!activity.isFinishing()) {
                 set_id(db.insert(SDIGENRE, SDIID, cv));
             }
         }
         application.getWritingToDataBaseFlag().compareAndSet(true, false);
         succeeded = true;
      } else {
      // Wait 100 millis
      try {
          Thread.sleep(100);
      } catch (InterruptedException e) {
          e.printStackTrace();
      }
  }
  </code></pre>
  
  <p>This seems to have worked well for quite a while.</p>
  
  <ol>
  <li>Is this the right way to go about getting around this issue?</li>
  <li>I have started to see these errors again; is there any advice on how to debug this issue?</li>
  </ol>
  
  <p>Thanks for any help,
  Julius.</p>