tags:

views:

50

answers:

2

Hello,

I need to implement a MultiKeyMap, where I can have 2 keys and a value. I was looking to Apache collections MultiKeyMap, but I'm not sure if it is the best one. My problem is that I need to use this MultiKeyMap in a Web environment, and the Apache implementation is not thread safe (and Collections.synchronizedMap(..) doesn't work).

Any idea? Thanks!

+1  A: 

Maybe I found a solution by using the MultiKey class from Apache collections:

Map myMap = Collections.synchronizedMap(new LinkedHashMap());
myMap.put(new MultiKey(1,3), "text");

In this way I can use a multi key synchronized approach!

andrew007
+1  A: 

Yeah, as andrew007 suggests, you can use MultiKey. If I were you though, I will implement my own class, name it something like BiKey, or even something more meaningful. One of the reason is that MultiKey is not generified.

To summarize, why don't you do something like:

ConncurrentMap<BiKey,Stuff> map = new ConcurrentHashMap<BiKey,Stuff>();

class BiKey{
    Key1 k1;
    Key2 k2;
    //let equals return k1.equqls&&k2.equals and implement hashCode accordingly
 }

ConcurrentHashMap scales really nice, and it has some useful operations that can come in handy.

Enno Shioji
I'd probably favor the Jakarta Commons implementation of hashcode()...
DerMike
@DerMike: Could be. But since it'll depend on the hashCode implementation of Key1, Key2, it's trivial to achieve what it offers... All you need to do is cache hashCode, that will be calculated as : int hash = k1.hashCode() ^ k2.hashCode();Well if k1 or k2 are mutable then it might get more complicated...
Enno Shioji