Search code examples
cachingoracle-coherence

Can Interface be used as key in Coherence Cache?


I have 2 different types of keys:

interface Key extends Serializable {
   String getName();
}

class KeyA implements Key {
    private String name;
    private int fieldA;
}

class KeyB implements Key {
    private String name;
    private int fieldB;
}

Can I use Key interface as a key in Coherence partitioned cache?


Solution

  • Yes, but you must ensure that all possible implementations of Key meet following preconditions (from Oracle Documentation):

    Cache keys must also provide an implementation of the hashCode() and equals() methods, and those methods must return consistent results across cluster nodes. This implies that the implementation of hashCode() and equals() must be based solely on the object's serializable state (that is, the object's nontransient fields).

    ...

    Some cache implementations (specifically the partitioned cache) use the serialized form of the key objects for equality testing, which means that keys for which the equals() method returns true must serialize identically.

    There is a good article by Patrick Peralta that explains this behavior.