How to avoid Memory Leaks?

2 views
Skip to first unread message

Rajnish

unread,
Jun 24, 2009, 7:33:30 AM6/24/09
to Technical Discussion
How can we avoid memory leaks in some of the scenarios mentioned
below?

Scenario #1:
A class in a framework has two methods to register and deregister
listener. The framework class uses ArrayList to register listener. Now
the user of the framework adds a listener but forgets to deregister
it. This may lead to memory leaks.

Scenario #2:
A class contains the cached data. Some of the data is static and some
is dynamic. How can we be sure that the cache does not contain unused
data.

Scenario #3:
A class is implemented as a stack. When the elements of stack are
popped then how can we be sure that that the stack should always be
clean and do not contain unused elements.


There could be more scenarios like this.

I have discussed these issues with some persons and came to conclusion
that we should use WeakHashMap as DataStructure to implement these.
Does using WeakHashMap will suffice for avoiding memory leaks?

Rajnish

unread,
Jun 29, 2009, 11:18:35 AM6/29/09
to Technical Discussion
Hi All

As per my analysis, we can use WeakHashMap to solve these type of
problems but we should carefully choose to use WeakHashMap. If some of
our data is static then we should not use them at any cost because
using them will loose the track of static data and we have to make
another call to retreive the same.

Also that depends on whether the memory is more important or
performance is our concern. For dynamic data we can surely use
WeakHashMaps.

Sometimes WeakHashMaps does not suffice as for for example in Scenario
#2, to implement Cache we can not blindly rely on WeakHashMaps and
should rather use simple HashMaps with LRU data structure implemented.


What are your opinions about my comments?
Reply all
Reply to author
Forward
0 new messages