TransWikia.com

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

Stack Overflow Asked by heaven on January 27, 2021

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

One 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.

Correct answer by simbleau on January 27, 2021

Add your own answers!

Ask a Question

Get help from others!

© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP