2

Are there any negative implications or known gotchas with storing static data (e.g. hashmaps, lists, objects) in Android as Java serialization streams?

By static data I mean data which does not change over time, not that the data is going to be in a static variable.

The serialization file is pre-generated and embedded into the app as a raw file resource (e.g. app/src/main/res/raw/my_serialized_data.ser) and then read with:

InputStream myData = context.getResources().openRawResource(R.raw.my_serialized_data);
ObjectInputStream ois = new ObjectInputStream(charMap);
myTable = (LinkedHashMap<String, String>) ois.readObject();
ois.close();

Apart from human readability issues I see no disadvantages since reading a serialised object from a file is bound to be faster than parsing data from something like a CSV or a SQLite database.

I have found this approach been used in some existing apps and currently consider using this approach in my own code. The motivation is that my data is bigger than 64K and putting it into a hashmap would require splitting the initialization code into methods that are maximum 64K in size.

ccpizza
  • 28,968
  • 18
  • 162
  • 169
  • Are you sure that you need all of this data in memory at once? If you only need a fraction of it, the SQLite option might be better, in that you could query and only load what you need. – CommonsWare Jan 12 '20 at 14:02
  • The data is gonna loaded on demand. The serialized stream is only gonna be loaded into memory when certain character translations are needed. – ccpizza Jan 12 '20 at 14:36

1 Answers1

0

I assume you have a very good reason to store such a big amount of data in memory. One important thing that it would do is a slow loading of the app. As it will init all static vars. For that i suggest a lazy loading technique. I like working with Singleton objects that loads only on with the first request of getInstance. In this way the load will be balanced in different timeslots of the app lifecycle.

Rami Khawaly
  • 126
  • 3
  • 14
  • I am deliberately not using static variables. The corresponding object is only going to be instantiated on demand and when it's done with its work it will be released for garbage collection. – ccpizza Jan 12 '20 at 14:38