I have a legacy application in which they are using a ConcurrentHashMap. Now as we know that concurrentHasMap is unordered, but reading objects as they were originally inserted is a requirement. The code I have has been there for sometime on production, thus I am looking for quick alternatives to just replace the collection and which could give me ordering as well. Basically looking for a very non-invasive solution which leads to minimum code changes. I searched the Web and got ConcurrentSkipListMap as an alternative, but it wont work for me. Reason being, by default it orders on the natural ordering of the key, which will not work for me. As my keys are string and I need ordered to be based on insertion not how string keys will be naturally ordered in the map.
Please suggest some alternatives at the earliest.
Thanks Anubhav
You should be able to use a LinkedHashMap to preserve insertion order and make it synchronized using the Collections.synchronizedMap(Map map) method.
public class Test {
Map<String, String> map = new LinkedHashMap<>();
Map<String, String> test = Collections.synchronizedMap(map);
public void test() {
test.put("Z", "Zed");
test.put("A", "Ay");
for (String s : test.keySet()) {
System.out.println(s);
}
}
public static void main(String args[]) {
try {
new Test().test();
} catch (Throwable t) {
t.printStackTrace(System.err);
}
}
}
This prints:
Z
A
as you require.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With