问题
To use intrinsic locking in Java you do
Object o = new Object()
...
sychronized (o) {
...
}
So one monitor already requires one Object i.e. 8 bytes or 16 bytes for 64bit (or 12 bytes for compressed ops and 64bit).
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>
?
回答1:
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.
"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.
That takes you back to segmenting your data, with one lock per segment, just like java.util.concurrency
does.
回答2:
To get a monitor, you need an object, so to get the functionality you're after, i.e. locking a set of primitive values, you need an object for the set.
Rather than creating an array of values and treating blocks of values as a set, with a separate Object
for the monitor, just create objects for the set of values.
It's the OO way.
来源:https://stackoverflow.com/questions/39379496/what-is-the-lowest-byte-usage-value-for-a-monitor-lock