同步(新Object())的用例 [英] A use-case for synchronized(new Object())

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

问题描述

在最近的答案中,我建议可以通过synchronizing来实现volatile的功能.包含变量的对象需要为volatile(询问者无法访问代码中的变量).

In a recent answer I suggested that it is possible to achieve the functionality of volatile by synchronizing on the object containing the variable we need to be volatile (asker does not have access to the variable in code).

这使我想到我实际上不需要阻塞包含的对象,我只需要实现内存屏障.当synchronized实现两者同步内存障碍时,如果我需要的只是内存障碍(在这种情况下),使用synchronized(new Object())实际上会更好达到我的记忆障碍确保锁永远不会被竞争?

This got me thinking that I actually don't need to block on the containing object, I just need to achieve a memory barrier. As synchronized achieves both synchronisation and a memory barrier, if all I need is the memory barrier (as in this case) would it actually be better to use synchronized(new Object()) to achieve my memory barrier and ensure the lock is never contended?

推荐答案

除了@assylias的优点外,还应考虑synchronized并没有达到规范的存储障碍.仅在这种情况下,才可以在当今的典型CPU内存体系结构上实现它.该规范仅保证当两个线程获得相同的锁时会发生什么.

In addition to @assylias's very good point, also consider that synchronized does not achieve a memory barrier by specification. It is only the case that this is how it is implemented on today's typical CPU-memory architectures. The specification only guarantees what happens when two threads acquire the same lock.

无论如何,如果您不关心规范,而只关心实际的实现,那么为什么不引入自己的volatile变量,并在需要内存屏障时直接写入该变量呢?只要我们讨论的是synchronized(new Object())想法所隐含的一组受约束的体系结构,您编写的 volatile就无关紧要.

Anyway, if you don't care about the specification, but only about the real-world implementations, then why not introduce your own volatile variable and simply write to it whenever you want a memory barrier? It is irrelevant which volatile you write to, as long as we're talking about a constrained set of architectures which is implied by your synchronized(new Object()) idea.

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

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