Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a synchronized AND sorted map object (LinkedHashTable)?

I am creating a servlet.Filter implementation wherein I lookup a user ID in a database based on the IP address before sending the request along to the servlet.

I want my filter to stash incoming requests into a map-like object if there is already a request from the same IP address which is being looked up on the database. Then when I get a response from the database, I will apply it to all requests for that IP address and send them on their way to the servlet.

The map-like object would need to be synchronized but also maintain the insertion order so that once I find the user ID all stashed requests "will be handled in the order in which they were received".

Going through the API there is a LinkedHashMap which would maintain the order fine but is not synchronized, the HashTable is synchronized but doesn't give any indication that it would maintain the right order.

Is there some kind of LinkedHashTable object I can use for this?

I am using Java 6.

like image 781
egerardus Avatar asked Dec 12 '22 23:12

egerardus


1 Answers

You can use synchronizedMap to wrap any Map implementation in a thread-safe container:

Map<K, V> synchronizedLinkedHashMap = Collections.synchronizedMap(new LinkedHashMap<K, V>());

You could also use a ConcurrentSkipListMap if you want to order your elements with a Comparator.

like image 191
Jeffrey Avatar answered Feb 22 '23 23:02

Jeffrey