Java locking of elements inside array
I have dynamic array of hashtables
Can I use synchronized for each of them separately? Like s开发者_如何学Pythonynchronized(array[1]) { code .. }, synchronized(array[2]) { code .. }
Thanks
You can certainly synchronize on the object in a particular position in the array writing:
synchronized (arr[x]) {
...
}
However, just be careful to make sure you understand whether this is doing what you want it to do.
This will lock on the particular object referenced by arr[x]. However, it won't buy you any thread-safety in terms of accesses to the array itself-- in other words, for example:
- while you're locking on the object at arr[x], another thread could still potentially change which object is at arr[x];
- if two threads simultaneously access the same position of arr (either to read which hash map/object is there, or to set a new one), there'll be a race condition.
I also tend to agree with akappa -- what you're doing sounds slightly unusual, and it might be better to rephrase your question as "what data structure do I need in order to do X" rather than assuming that an array of hashmaps is the appropriate one from the outset?
Sure, but it's better to use a concurrent map os a concurrent skip list for throughput concerns, if you can.
BTW, if you provide us a bit of context, we can suggest you a (maybe) better data organization and structure.
精彩评论