0

I'm doing a app in android with Rest and observer design pattern, when I do a Rest request I cache the response but some of this response object I want to let the objects in memory permanently until the application is destroyed.

So I have been thinking in create a class with just public static variables (some projects use this kind of class to declare constants Strings) to set them and then I could use it in memory. Something like this:

public class Memory {

    public static HashMap<String, PersonDto> people;
    // This object could have another complex object as ArrayList or HashMap...
    public static LocationsDto locations;
    ...
}

All I want to know if this could be a bad practice to do what I am trying to solve.

  • 2
    Possible duplicate of [What is the best way to implement constants in Java?](http://stackoverflow.com/questions/66066/what-is-the-best-way-to-implement-constants-in-java) – hahn Apr 21 '16 at 07:36

2 Answers2

1

It depends on the usage of these objects. The most important aspect being: is there a possibility of concurrent modification/access? If so, then you should implement some kind of synchronization.

If these objects are guaranteed to be constructed before any access to them and they will not change their state afterwards, then your approach would be fine in terms of synchronization issues.

For instance, if your Dto objects are immutable and the hashmap will not be modified concurrently, than you are safe. If the hashmap needs to support concurrent access/modification, then take a look at the ConcurrentHashMap.

Selçuk Cihan
  • 1,979
  • 2
  • 17
  • 30
  • At least initially it will be immutable, all I want is a faster access to some objects of the rest response but I want to use it globally in my application. I only will create the new instance of this object when the rest service response me, then I will use this static variables. – Ricardo Romero Benítez Apr 21 '16 at 08:02
1

While its not definitively a bad practice, it is usually considered as a design flaw to have global mutable state. You can find a lot of information about why it is so. To me the most important disadvantages are problems with testability and unpredictable program state. If you are still going to use it, you would also want to synchronise access to the static fields.