Dhanesh Khurana
Dhanesh Khurana

Reputation: 159

Storing Object States in java

I need to store a thousands objects states in a file, at the end of a time-cycle and bring them back to life in main memory with start of every new cycle.

so there are two ways I have thought of so far :

for example storing these objects directly as

class UsingClassObjects {
    private String name;
    private int age;
    private long rollNo;
    private long credits;

}

or create a hashMap to store the states as:

class UsingHashMap{
    HashMap<Integer, HashMap<String, HashMap<Long, Long>>> data = new HashMap<Integer, HashMap<String, HashMap<Long, Long>>>();

}

So which of these two approaches is better memory and efficiency wise and why ?

and is there any even a better way to do so ?

and would serializing the object/s affect the performance rather than writing states to a plain text file, if I use the HashMap?

Upvotes: 0

Views: 1358

Answers (2)

Ankush soni
Ankush soni

Reputation: 1459

To store the state in an HashMap is not a good option because: 1. In the end it is an object and it will dead if your server is crash or you stop the JVM.

  1. If you are storing 1000 of object in HashMap which will increare the memory and there are chances to get Out of Memory issue.

  2. HashMap will consume lot of memory for each entry object in it.

Hence I would recommend to use Java Serialization to store the state of an object which will preserve the state even if JVM is down.

Upvotes: 1

Geek
Geek

Reputation: 23409

Serialize the object and store in the File is much better than your HashMap approach as it can be wasteful. Also it will be trivial to serialize/deserialize a POJO if it is not complex. You can use a DB too and that can be helpful. You can use a Cache like REDIS also.

Upvotes: 1

Related Questions