In one of my classes say SimpleDate
, I need some objects like DateFormat
which may be used a lot of time from various instances. For this reason, I would like to make them static.
However, I would also want that these objects should be garbage collected if needed when we do not have any instances of the SimpleDate
object left. A static declaration would not allow that to happen.
So basically I want something like
private weakstatic DateFormat df = DateFormat.getInstance();
This DateFormat
instance should be eligible for garbage collection if no objects of the declaring class exist anymore. Also, it should be reinitialised whenever any new instance of the declaring class is created. This way we can avoid recreation of objects used repeatedly but also free the memory when they are not needed anymore.
I know it should be possible using WeakReferences. However, I am not able to figure out a way to do it.
Edit: DateFormat may be a wrong candidate here since it is not thread safe. But it should be as thread safe as declaring them static.
The idea is that we often make variables static that are used across instances. And these variables linger for ever till the application process dies. So if you just touch a class, its static variables remain in memory forever.