同步对不可变整数对象的访问 [英] Synchronizing access to Immutable Integer object

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

问题描述

代码段-1

class RequestObject implements Runnable
{
    private static Integer nRequests = 0;

    @Override
    public void run()
    {       
        synchronized (nRequests)
        {
            nRequests++;
        }
    }
}

代码段-2

class RequestObject implements Runnable
{
    private static Integer nRequests = 0;
    private static Object lock = new Object();

    @Override
    public void run()
    {       
        synchronized (lock)
        {
            nRequests++;
        }
    }
}

尽管第二个代码段在不引起任何争用条件的情况下运行良好,但第一个代码段未能成功同步同一类(RequestObject)的不同实例之间对静态数据成员的访问.有人可以对此进行更多说明.我想了解为什么第一种方法行不通.

While the second code snippet is working fine without causing any race conditions, the first one isn't successful in synchronizing access to the static data member between different instances of the same class(RequestObject). Could somebody throw more light on this. I would like to understand why the first approach isn't working.

我最初的实现是第一个.后来我在 https://stackoverflow.com/a/2120409/134387 中看到.

My original implementation is the first one. The later I saw in https://stackoverflow.com/a/2120409/134387.

推荐答案

您正在不断创建新的Integer对象,然后将其与之同步,这至少使考虑它变得非常混乱.因此,您可以得到以下情形:

You are constantly creating new Integer objects, which you then synchronize on, which at least makes it extremely confusing to think about it. So you can get the following scenario:

线程A保留了nRequests的当前值(假设为0)

Thread A gets hold of the current value of nRequests (lets say 0)

线程B排队等待相同的值(0)

Thread B queues for the same value (0)

线程A增加nRequests(至值1)

线程C拥有新值并对其进行同步,增加并释放该值.

Thread C gets hold of the new value and synchronizes on it, increases it and lets go of the value.

线程A在0处松开了监视器

Thread A lets go of the monitor on 0

线程B在0上同步并增加到1,从而覆盖了C的更改

Thread B synchronizes on 0 and increases it to 1, overwriting the changes of C

使用第二种方法,您只有一个对象,每个人都必须在该对象上进行同步.正是您想要的.

With the second approach you have a single object that everybody has to synchronize on. Which is exactly what you want.

这篇关于同步对不可变整数对象的访问的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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