Reputation: 97
How are these code snippets different from each other:
Snippet 1: HashMap map1= abc() ;
Snippet 2: HashMap map2= new HashMap();
map2 = abc();
I'm getting OutOfMemoryError in my application. Can the reason of this error due to the implementation of Snippet 1 in my code?
Edit: Added implementation of abc()
public HashMap abc(){
HashMap rMap = null;
StringBuffer sQuery = new StringBuffer("");
sQuery.append(" SELECT DISTINCT ABC ,DEF, ");
sQuery.append(" XYZ, ID, NAME ");
sQuery.append(" FROM TABLE1");
Query query = new Query( sQuery.toString());
List rList = query.executeSelect();
if (rList != null && rList.size() > 0) {
Iterator listIter = rList.iterator();
Map map = null;
rMap = new HashMap();
while (listIter.hasNext()) {
map = (HashMap) listIter.next();
String key = map.get("ABC") + "%"+ map.get("DEF")+"%"+map.get("XYZ");
if( rMap.containsKey(key)){
LinkedHashMap sMap = (LinkedHashMap) rMap.get(key);
sMap.put(map.get("ID"), map.get("NAME"));
rMap.put(key, sMap);
}else{
LinkedHashMap sMap = new LinkedHashMap();
sMap.put(map.get("ID"), map.get("NAME"));
rMap.put(key, sMap);
}
}
}
return rMap;
}
Upvotes: 0
Views: 131
Reputation: 1
Basically in snippet 2 at the beginning you just initialize the map2 for nothing. After second step it will just point to another address and older one will be garbage collected.
Upvotes: 0
Reputation: 1386
In Snippet 2
you create an extra instance which would be eligible for garbage collection on the next statement. So basically they're the same and it shouldn't cause a memory leak.
Try running a profiler to check memory map or increase the heap size.
Upvotes: 1
Reputation: 1680
Your problem seems to be in another part of your code.
Try setting an automatic heapdump when a OutOfMemoryError
occurs. See this Using HeapDumpOnOutOfMemoryError parameter for heap dump for JBoss
Then, fire the exception running your code.
Last thing is to analyze the dump with a tool like Eclipse Memory Analyzer https://eclipse.org/mat/ and look for big objects o a big number of instances of small objects. There are lots of tutorials about how to analyze a memory dump: http://www.vogella.com/tutorials/EclipseMemoryAnalyzer/article.html
Upvotes: 0