Using putAll(TreeMap) with BinaryObjects

classic Classic list List threaded Threaded
2 messages Options
Григорий Доможиров Григорий Доможиров
Reply | Threaded
Open this post in threaded view
|

Using putAll(TreeMap) with BinaryObjects

Hello.
As I know it's recommended to use putAll with TreeMap to avoid deadlocks (is there any other reasons?). If so, how to deal with .withKeepBinary cache, where you have to provide Map of BinaryObjects, which are not Comparable, and thus couldn't be put in TreeMap?

Also, why deadlocks could happen with HashMap, and why using TreeMap prevents it?
ptupitsyn ptupitsyn
Reply | Threaded
Open this post in threaded view
|

Re: Using putAll(TreeMap) with BinaryObjects

The reason for any deadlock (local or distributed) is taking locks on same objects in different order, e. g:
Thread 1 locks A, B
Thread 2 locks B, A
  => thread 1 holds A and waits on B, thread 2 holds B and waits on A

When doing putAll, Ignite iterates over the provided map and locks keys in the iterator order.
TreeMap is sorted, so it solves the problem automatically. Locks are taken in the same order on all nodes/threads, preventing deadlocks.
HashMap can reorder elements arbitrarily, on the other hand, causing random deadlocks.


For withKeepBinary cache you have two options:
- LinkedHashMap preserves insertion order. Make sure you always populate the map in the same order.
- TreeMap with Comparator. Implement Comparator that sorts your keys the right way, probably based on a particular field of the BinaryObject



On Wed, Feb 12, 2020 at 12:12 AM Григорий Доможиров <[hidden email]> wrote:
Hello.
As I know it's recommended to use putAll with TreeMap to avoid deadlocks (is there any other reasons?). If so, how to deal with .withKeepBinary cache, where you have to provide Map of BinaryObjects, which are not Comparable, and thus couldn't be put in TreeMap?

Also, why deadlocks could happen with HashMap, and why using TreeMap prevents it?