Skip to content
Advertisement

Reducing potential excess of garbage when using primitive types with generics?

I have this system that allows me to create and implement type-safe variables per-player. Each variable is defined along the lines of

@Foo
public static final Bar KILLS = new Bar();

The annotation marks the variable to be picked up at runtime for registration purposes. These variables are essentially static mutator methods that adjust the underlying value for the player in question like so

KILLS.set(player, 10);

The system works great however, each type (Object, int, String, etc) is backed by a mutable type which is lazily loaded into the respective player’s variable map. I was curious on the potential garbage issues this design may introduce as player count scales upward. I know some things are unavoidable due to java’s autoboxing mechanism but maybe there is some room for improvement elsewhere. I’m not entirely familiar with the java memory model so excuse my explanation or lack thereof.

EDIT:

To give a bit more clarity, each variable type extends a parent class and provides a type of T respectively. These children classes are then given access to override required methods which allow them to mutate the value of the concerning player variable. Visual of class hierarchy

Advertisement

Answer

Firstly, I would like to say I am a bit confused by your mention of “garbage issues”, because your context is not entirely clear whether you’re referring to Java’s implicit garbage collection of runtime memory or whether you’re concerned about this registration data is piling up somewhere else, like a database.

If you’re referring to Java’s runtime memory management: Java is (as you probably know) automatically garbage collected but you can suggest (with no guarantee whatsoever) Java to collect garbage at any time with System.gc(). This is almost always a micro-optimization and provides little to no real benefit as Java is already amazing at determining the correct time to do garbage collection without you. I wouldn’t even bother worrying about it in Java.

If you’re referring to an external model of storage of this data, I would be concerned. By having an abstract ‘setter’ method, for lack of better terms, you’re exposing bugs or side effects to ravage that memory. That is something that needs to be dually managed to be as bug-free as possible on the Java implementation but also you need to manage the memory on the external storage yourself.

Nonetheless, a situation like this is almost certainly indicating the backing code requires restructuring and more direction. This abstract setter method is (in my opinion) a code smell.

User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement