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.
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.
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