同步语句的NullPointerException [英] NullPointerException on synchronized statement

查看:142
本文介绍了同步语句的NullPointerException的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我尝试在下面的代码中同步对象:

I tried to synchronize on an object in my code below:

public void myMethod() {
    synchronized (globalObj) {
        //Do something here
    }
}

代码在一个线程中执行。问题是,另一个线程可能将'globalObj'设置为null。然后,当'globalObj'被其他线程设置为null时,'synchronized(globalObj)'将抛出NullPointerxception。

The code is executed in one thread. The issue is that, another thread may set 'globalObj' to null. Then, 'synchronized (globalObj)' will throw NullPointerxception when 'globalObj' has been set to null by other threads.

在对象上同步的最佳做法是什么,因此NullPointerException不会被抛出?

What's the best practice to synchronize on an object so NullPointerException will not be thrown?

谢谢。

推荐答案

你不应该在可以更改的引用上进行同步。如果允许另一个线程替换 globalObj ,这意味着您可以锁定旧的 globalObj ,而另一个线程可以工作在完全不同的一个 - 锁根本没有帮助你。

You should not be synchronizing on a reference that itself may be changed. If another thread is allowed to replace globalObj, that means you might hold a lock to the old globalObj while another thread works on an entirely different one - the lock doesn't help you at all.

你应该做的是有一个单独的对象为此目的:

What you should do instead is have a separate Object for this purpose:

static final Object lockObj = new Object();

public void myMethod() {
  synchronized (lockObj) {
    // do something with globalObj here
  }
}

由于 lockObj 永远不会改变,你总是会使用相同的锁 - 没问题。

Since lockObj never changes, you'll always use the same lock - no problems.

这篇关于同步语句的NullPointerException的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆