1

Need to have a queue and like mapSet to having unique key, so that it supports

queue.put(key, value) //<== put in the queue and keep the order (it become last in the queue)
queue.get(key)
queue.remove(key)

and it can also do something like

queue.pop() // remove from head

seems it could be implemented with LinkedHashMap but it is not thread safe. Any other data structure in kotlin may be used for this case? or LruCache?

lannyf
  • 9,865
  • 12
  • 70
  • 152
  • The Javadoc for LinkedHashMap says you should use `Collections.synchronizedMap` if you want a synchronized version. https://docs.oracle.com/javase/8/docs/api/java/util/LinkedHashMap.html – kaya3 Aug 08 '20 at 10:36
  • @kaya3 thx!, it may not keep the order? Looking at LruCache, seems it could be the one to use, but have not figure out how to "traverse" it if want to printout the list in the LruCache. – lannyf Aug 08 '20 at 11:06
  • The usual answer to multi-thread maps is of course [ConcurrentHashMap](https://docs.oracle.com/en/java/javase/11/docs/api/java.base/java/util/concurrent/ConcurrentHashMap.html) — but its elements “are not ordered in any particular way”, so wouldn't be suitable for this.  As @kaya3 says, you could use a synchronised wrapper around LinkedHashMap: the wrapper merely provides synchronisation and doesn't affect the semantics of the underlying implementation, so that could work well.  A more specialised class could give better performance, but I'm afraid I'm not aware of one… – gidds Aug 08 '20 at 11:36
  • that's what the android.util.LruCache, which is thread-safe and keep the order internally. ``` public class LruCache { private final LinkedHashMap map; ``` – lannyf Aug 08 '20 at 16:21

0 Answers0