简体   繁体   中英

Java synchronized passing object to alien method

I have an object passed into a function which passes a delayed runnable to a handler.

I can lock the object when it gets passed in and when it gets changed using the lock object but then the object needs to get passed out to an 'alien' method upload.

How can I ensure this alien method upload does not break the thread safety of my object?

It has objects passed in from elsewhere not just this delay thread so the object lock is not valid and it encompasses quite a lot of functionality so I'm concerned about locking the entire call with the lock object.

private ContentValues mEvent;
protected final Object mEventLock = new Object();

public void delayFunction(final Values e) {

    // Sanity check
    if (e == null) {
        return;
    }

    synchronized (mEventLock) {
        mEvent = e;
    }

    this.handler.postDelayed(new Runnable() {

        @Override
        public void run() {

            if (prefs != null) {
                final String refs = prefs.getPrefs();
                if (refs != null && refs != "") {

                    log.d("refs field: '%s'", refs);

                    synchronized (mEventLock) {
                        mEvent.remove(refs);
                        mEvent.put(refs, 1);
                    }
                }
            }

            synchronized (mEventLock) {
                // Upload event.
                upload(mEvent);
            }

        }
    }, INSTALL_DELAY);
}

I am not sure I understand what you are trying to achieve in your code:

  • delayFunction starts by assigning e to mEvent
  • then you modify mEvents
  • then you upload mEvents

Why don't you simply make a local copy of e and work on that copy without synchronization?

Also, mEvent could be modified by another thread between mEvent = e and the runnable execution because you exit the synchronized block: your runnable would then be working on another e and you will have missed an upload.

But maybe that's on purpose.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM