2

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);
            }
        }
    }
  • I was wondering the same. I don't think it's needed as the service is a singleton. It's the SyncAdapter that can run multiple instances (for for multiple accounts, and in parallel if so specified). Perhaps this question would get a better response if asked on Stack Overflow. – Paul Lammertsma Jul 6 '16 at 12:54
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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.