Below is a sample code i captured from android doc
Per service instance onCreate will be called only once. Ref: here and here
The synchronization and singleton doesn’t make any sense to me in this circumstance. Very recently i asked another question on google document here
If this is again wrong, probably i need to limit myself to just take calling conventions from their documents and ignore their logic.
Sorry to running through Google doc with community in quick succession. I just want to correct myself on how much i should take from these documents.
public class SyncService extends Service {
// Storage for an instance of the sync adapter
private static SyncAdapter sSyncAdapter = null;
// Object to use as a thread-safe lock
private static final Object sSyncAdapterLock = new Object();
/*
* Instantiate the sync adapter object.
*/
@Override
public void onCreate() {
/*
* Create the sync adapter as a singleton.
* Set the sync adapter as syncable
* Disallow parallel syncs
*/
synchronized (sSyncAdapterLock) {
if (sSyncAdapter == null) {
sSyncAdapter = new SyncAdapter(getApplicationContext(), true);
}
}
}
1
It is necessary. Note that sSyncAdapter is a STATIC variable.
This means there is one of them per application, not one per instance of the object.
Consider the situation when 2 (or more) SyncService objects are created at the same time. In that case, there would be a race and you could get two SyncAdapter objects created (with one a dangling reference not assigned to sSyncAdapter).
AND – even if external logic of your application prevents ever creating two SyncService at the same time, there is another reason for the lock. It creates a memory barrier, which ‘publishes’ the assignment to sSyncAdapter to other threads. I’m presuming there is other (threaded) code that accesses sSyncAdapter. The lock / unlock is needed to force the processor cache management to flush the data so its seen by other threads.