Java 虚拟机器人
Java Virtual Machine Tutorial
Selected Reading
Java Virtual Machine Tutorial
- JVM - Discussion
- JVM - Useful Resources
- JVM - Quick Guide
- JVM - Memory Leak in Java
- JVM - Tuning the GC
- JVM - Generational GCs
- JVM - Garbage Collection
- JVM - JIT Optimisations
- JVM - 32b vs. 64b
- JVM - Compilation Levels
- JVM - The JIT Compiler
- JVM - Runtime Data Areas
- JVM - Class Loader
Selected Reading
- Who is Who
- Computer Glossary
- HR Interview Questions
- Effective Resume Writing
- Questions and Answers
- UPSC IAS Exams Notes
JVM - Memory Leak in Java
Java Virtual Machine - Memory Leak in Java
We shall discuss about the memory leak concept in Java in this chapter.
The following code creates a memory leak in Java −
void queryDB() { try{ Connection conn = ConnectionFactory.getConnection(); PreparedStatement ps = conn.preparedStatement("query"); // executes a SQL ResultSet rs = ps.executeQuery(); while(rs.hasNext()) { //process the record } } catch(SQLException sqlEx) { //print stack trace } }
In the above code, when the method exits, we have not closed the connection object. Thus, the physical connection remains open before the GC is triggered and sees the connection object as unreachable. Now, it will call the final method on the connection object, however, it may not be implemented. Hence, the object will not be garbage collected in this cycle.
The same thing will happen in the next until the remote server sees that the connection has been open for a long time and forcefully terminates it. Thus, an object with no reference remains in the memory for a long time which creates a leak.
Advertisements