简体   繁体   English

Java同步将对象传递给外来方法

[英]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. 我可以在对象传入和更改时使用lock对象锁定该对象,但随后需要将该对象传递给“外星人”方法上传。

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. 它具有从其他地方传入的对象,而不仅仅是这个延迟线程,因此对象锁定无效,并且它包含很多功能,因此我担心使用lock对象锁定整个调用。

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 delayFunction开始通过分配emEvent
  • then you modify mEvents 然后您修改mEvents
  • then you upload mEvents 然后您上传mEvent

Why don't you simply make a local copy of e and work on that copy without synchronization? 您为什么不简单地制作e的本地副本并在不同步的情况下处理该副本?

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. 此外, mEvent可以通过与另一个线程修改mEvent = e和运行执行,因为你退出synchronized块:您可运行的客户将会在另一个工作e ,你会错过上传。

But maybe that's on purpose. 但这也许是故意的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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