Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

FrameDecorator 单例写法线程安全问题 #777

Open
wants to merge 2 commits into
base: master
Choose a base branch
from

Conversation

Shouheng88
Copy link

    public static FrameDecorator getInstance(final Context context) {
        if (instance == null) {
            if (Thread.currentThread() == Looper.getMainLooper().getThread()) {
                instance = new FrameDecorator(context, new FloatFrameView(context));
            } else {
                try {
                    synchronized (lock) { // 1
                        mainHandler.post(new Runnable() {
                            @Override
                            public void run() {
                                if (instance == null) { 
                                    instance = new FrameDecorator(context, new FloatFrameView(context));
                                }
                                synchronized (lock) {
                                    lock.notifyAll();
                                }
                            }
                        });
                        lock.wait(); // 2
                    }
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }
        return instance;
    }

2 处释放锁的时候 block 到 1 处的子线程仍然有可能获取到锁并进入同步代码块,虽然实例化操作在主线程中线性执行,但是可能在消息队列中存在多条实例化消息导致单例非线程安全。

解决办法是在主线程 post 消息中增加一层判断,这样主线程线性执行,无线程安全问题,避免多次创建单例

@tencent-adm
Copy link
Member

CLA assistant check
Thank you for your submission, we really appreciate it. Like many open source projects, we ask that you sign our Contributor License Agreement before we can accept your contribution.


wangshouheng seems not to be a GitHub user. You need a GitHub account to be able to sign the CLA. If you have already a GitHub account, please add the email address used for this commit to your account.
You have signed the CLA already but the status is still pending? Let us recheck it.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants