监视器锁定的最低字节使用率是多少? [英] What is the lowest byte usage value for a monitor lock?

查看:91
本文介绍了监视器锁定的最低字节使用率是多少?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

要在Java中使用固有锁定,请执行

To use intrinsic locking in Java you do

Object o = new Object()
...
sychronized (o) {
 ...
}

因此,一个监视器已经需要一个对象,即 8个字节或64个字节的16个字节(或12个字节的压缩操作和64位).

So one monitor already requires one Object i.e. 8 bytes or 16 bytes for 64bit (or 12 bytes for compressed ops and 64bit).

现在假设您要使用许多此类监视器,例如一种阵列,该阵列可以在某些区域同步,并且比(c0)具有更好的并发性(基于条目).那么,最有效的方法是什么呢?我能以某种方式对2个条目使用2个嵌套锁,对8个条目使用3个嵌套锁吗?或者我可以使用每个线程一个锁",例如在ConcurrentHashMap<array_index, lock>吗?

Now assume you want to use lots of these monitors e.g. for an array which one can synchronize over certain areas and that has better concurrency (entry based) than Collections.synchronizedList. Then what is the most efficient way to implement this? Could I somehow use 2 nested locks for 4 entries or 3 for 8 etc? Or could I make use of "one lock per thread" e.g. in a ConcurrentHashMap<array_index, lock>?

推荐答案

根据访问模式,可以通过分割数据结构并使用单个内部锁来保护多个元素,从而以更少的锁来提高并发性. java.util.concurrent软件包中提供的一些并发集合中使用了此技术.

Depending on access patterns, you might increase concurrency with fewer locks by segmenting your data structure and using a single intrinsic lock to guard multiple elements. This technique is used in some of the concurrent collections provided in the java.util.concurrent package.

我能以某种方式对2个条目使用2个嵌套锁,对8个等等使用3个嵌套锁吗?"听起来您打算像对待条目索引中的某个位一样对待每个锁:如果设置了该位,则获取该锁;否则,请执行以下操作.如果很清楚,请跳过它.这行不通.考虑一下索引0.将不会获取任何锁,并且您将没有并发控制.

"Could I somehow use 2 nested locks for 4 entries or 3 for 8 etc?" It sounds like you are planning to treat each lock like a bit in the entry index: if the bit is set, acquire the lock; if it's clear, skip it. This won't work. Think about index 0. No locks would be acquired and you'd have no concurrency control.

您可以通过加倍锁的数量(每位都有一个设置"和清除"锁)使其起作用",但这仍然不是一个好主意,因为您将浪费锁并获得差的并发性.最外层的锁将保护一半的条目.随后获取的任何嵌套锁都是无用的,因为其他线程已从该段中排除.

You could make it "work" by doubling the number of locks (have a "set" and "clear" lock for each bit), but it's still a bad idea because you'd be wasting locks and getting really poor concurrency. The outermost lock would guard half the entries. Any nested locks acquired subsequently would be useless, because other threads are already excluded from that segment.

这使您回到分段数据的方式,每个分段一个锁,就像java.util.concurrency一样.

That takes you back to segmenting your data, with one lock per segment, just like java.util.concurrency does.

这篇关于监视器锁定的最低字节使用率是多少?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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