I have three services in my Android app that are fired by two broadcast receivers. The first two write onto a file and are fired by one broadcast receiver so I can make sure that they are executed one after the other (via Context.sendOrderedBroadcast()). The third one is on its own and is fired by a separate broadcast receiver, but reads from the same file that the first two write on.
Because the broadcast receivers may be fired at the same time or nearly the same time as each other, the file might also be accessed concurrently. How can I prevent that from happening? I want to be able to either read first then write or write then read. I’m just not sure if this problem is similar to Java concurrency in general because android services, if I’m not mistaken, are an entirely different beast.
First of all, I shouldn’t have done the file I/O in the main UI thread which is the case with
Services. It should be done in another thread, like anAsyncTask.Secondly, the
ReentrantLockmethod is so much easier. When locked, it tells the other threads accessing the same resource to wait, and proceed only when the lock has been released. Simply instantiate anew ReentrantLock()and share that lock among the methods that read to or write from the file. It’s as easy as callinglock()andunlock()on theReentrantLockas you need it.