I need to lock some map items simultaneously without any other thread intercepting. I mean I want to lock 10 items and I think I need to use a loop but I don't want to be prevented from locking remaining 5 items after I locked the 5th item. Do I need to use another map-independent lock wrapping the locking code block?
1 Answers
I don't think there's any way to prevent a potential deadlock in your use case beside making sure to lock items in the same order (I think this is what you want to prevent).
Before you start to lock just make sure you applied some ordering to the keys to be locked (like natural ordering by just using a List and Comparator). In this case all locks will be acquired in the same order. Still you might run into the situation where, potentially, one operation will acquire 1, 2, 3 and the other operation will acquire 2, 3, 4. That said the first operation will successfully acquire 1 but might be blocked at 2.
Question is, what is your use case? You're probably better of using a different approach. If the keys ALWAYS belong together, it might be more useful to apply Data Affinity and use an EntryProcessor. For other use cases there might still be a better way instead of using multiple locks. Locks are commonly a bad idea in multithreaded systems and they don't do any better in highly parallel, distributed systems.