I am new to Java, and am working on a Public Transit Java app as a first small project.
I am loading transit data in from a server through an XML api (using the DOM XML API). So when you call a constructor for say a BusStop(int id), then the constructor loads the info about that Stop from the server based on the id provided. So, I am wondering about a couple things: how can I make sure I don’t instantiate two BusStop objects with the same id (I just want one object for each BusStop)?
Also does anyone have recommendations on how I should load up the objects, so I don’t need to load the whole database every time I run the app, just the BusStop, and relevant Arrivals and BusTrips objects for that stop? I have done C++ and MVC PHP programming previously, but haven’t had experienced loading large numbers of objects with circular object references etc.
Thanks!
I wouldn’t start the download/deserialization proces in a constructor. I would write a manager class per entity type with a method to fetch a Java object for a given entity based on its ID. Use a
HashMapwith the key type as your entity ID and the value type as the Java class for that object. The manager would be a singleton using your preferred pattern (I would probably use static members for simplicity).The first thing the fetch method should do is check the map to see if it contains an entry for the given ID. If it has already fetched and build this object, return it. If it has not, fetch the entity from the remote service, deserialize the object appropriately, load it into the
HashMapby the specified ID, and return it.Regarding references to other object I suggest you represent those as IDs in your Java objects rather than storing them as Java object references and deserializing them at the same time as the referencing object. The application can lazily instantiate those objects on demand through the relevant manager. This reduces problems through circular references.
If the amount of data is likely to exceed available RAM on your JVM you’d need to consider periodically removing older objects from the map to recover memory (confident they would be reloaded when required).