I would like to create an LRU cache that is backed by the shared preferences. Basically I would like to store a specific number of strings (around 20) and have an LRU behavior.
I know that LinkedHashMap
is an LRU in java but is there a way to achieve what I want somehow backing up the LRU in the shared preferences in a clean way?
Asked
Active
Viewed 474 times
4

Jim
- 18,826
- 34
- 135
- 254
-
if you're using Guava, they've got maps with delegating load events: https://stackoverflow.com/questions/3802370/java-time-based-map-cache-with-expiring-keys – eduyayo Jul 03 '17 at 15:17
-
@eduyayo: I am not using Guava. – Jim Jul 03 '17 at 15:30
-
You can add a timestamp to each keys or values, call `mSharedPreferences.getAll()` to see al the keys and values and use `remove().commit()` to get rid of the last one. Should be fast enough as long as you don't have too many elements. – Endre Börcsök Jul 03 '17 at 15:33
1 Answers
0
A much cleaner way would be, maintain a LinkedHashMap
in the application. When ever there is a any operation on LinkedHashMap
, convert it into String ArrayList and save it into SharedPreferences and vice-versa.

KR_Android
- 1,149
- 9
- 19
-
Yes I am fine with the LinkedHashMap. My question is how would I "glue" the LinkedHashMap with the SharedPreferences in a clean way – Jim Jul 03 '17 at 16:58
-
-
You have to write a wrapper function which will push linkedhashmap into shared preference and read it back – KR_Android Jul 03 '17 at 17:01
-
When exactly should this commits occur though? When should the linked hashmap should be created in the activity lifecycle and when should an update to the linkedhashmap should commit to the shared preference? – Jim Jul 03 '17 at 17:28
-
-
In your answer you recommend to convert and save on any alteration of the LRU though – Jim Jul 03 '17 at 17:42
-
It depends on your application..If you are using it for single activity than its recommend it do it on activity life cycle method Buy if you are using across application than you should so it on alteration – KR_Android Jul 03 '17 at 17:46