0

I have a DBApdater class that is accessed through many AsyncTasks. Each operation defined on the DB has to call a function written in the DBAdappter class called open, insert or delete from the db, and then close the DB. If one Async object has called open through an object of the DbApater how can i prevent a second AsyncTasks to call open until the first AsyncTask has called close on the DB. Could i use a lock like public static Object myLock =new Object();

and in the open mentod write

public void open()
{
      synchronizaed(myLock.getClass)
      {///Open the DB  
      }
}

public void close()
{
    synchronizaed(myLock.getClass)
      {///close the DB  
      }
     notify();
}

would this code work. Basically the calling class would obtain a lock on the open menthod and release it only when close is called.

Kind Regards,

Muhammad Mateen

4
  • Usually, you would synchronize on myLock, not myLock.getClass(). notify() is not required. And myLock should definitely not be public. Commented Feb 15, 2012 at 11:40
  • That code will just prevent concurrent calls to open and close. It will not prevent for example, Thread1 opens the database, Thread2 modifies the database, Thread1 modifies the database, Thread2 closes the database. Commented Feb 15, 2012 at 11:49
  • ContentProvider:s are your friends - not mortal enemies that must be defeated by littering your Activity classes with SQLiteDatabase object references. Commented Feb 15, 2012 at 13:12
  • Possible duplicate questions here and here, see if those help you out. Commented Feb 16, 2012 at 1:03

2 Answers 2

0

Synchronizing the access to database via open() and close() methods is the right approach in my mind. This should work.

Sign up to request clarification or add additional context in comments.

Comments

0

I am not familiar with the specifics of thread safe communication in an android development, but looking at your suggestion from a C# developers point of view it makes sense.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.