SlideShare ist ein Scribd-Unternehmen logo
1 von 12
Resource Leaks
in Java
What Is a Resource Leak?
And Why You Should Care About Them
What Is a Resource Leak?
A resource leak is an erroneous pattern of
resource consumption where a program does
not release resources it has acquired. Typical
resource leaks include memory
leaks and handle leaks.
Why You Should Care
Consequences to users:
‱ Poor performance
‱ Poor stability or reliability
‱ Denial of service
Consequences to developers:
‱ Time consuming to find, even with a debugger
‱ Can reduce reliability of the testing suite by interrupting
test runs
Question:
Java is a modern language with a garbage
collector to take care of resource
management. Doesn’t that mean that I don’t
need to worry about resource leaks?
Answer:
No!
The garbage collector (GC) can help ensure
unused objects on the heap are reclaimed
when they are no longer used. But:
‱ It can't guarantee that you will have the resources you
need, when you need them
‱ Reference subtleties can “trick” the GC into leaving
unexpected objects on the heap
‱ Many objects, such as database connections and file
handles, are managed by the operating system - not Java
Consider This Code Snippet*
Note:
‱ It tries to handle exceptions while shutting down the database
‱ It creates Connection and Statement objects on lines 43 and 44
‱ This method is associated with a task and may run repeatedly
* From an open source project
Best Case:
1. L43: “con” allocated,
connected to db.
2. L44: statement created,
“SHUTDOWN” executed
3. Assuming no exceptions occur, the method exits
4. Eventually, the GC detects that the handles are no longer
used and schedule calls to their finalizers
5. In a later pass, the finalizers will be called, releasing the
underlying handles
6. All is good
Reality:
1. L43: “con” allocated,
connected to db.
2. L44: statement created,
“SHUTDOWN” executed
3. Assuming no exceptions occur, the method exits
4. The application continues to work with the database in
other methods
5. Eventually, other methods are unable to get new
statement handles and fail
6. The GC never gets to detect that the handles are no longer
used, or scheduled calls to their finalizers never get run
To Avoid the Problem:
Explicitly close the handles
Replace lines 43 and 44 with something like the following
code:
Connection con = null;
Statement stmt = null;
try {
con = DriverManager.getConnection(<url>);
stmt = con.createStatement();
stmt.execute("SHUTDOWN");
// Perhaps some catch blocks for SQLException, etc.
} finally {
// if you’re paranoid, put these in a separate try/catch for SQLException
if (stmt != null) { stmt.close(); }
if (con != null) { con.close(); }
}
Note that Java 7 has a simplified “try-with-resources”
statement.
In Short

1. Remain vigilant about resource usage
‱ Explicitly close resources when you are done with them
‱ Be careful to handle exceptional cases, too!
2. Use tools to identify cases that you miss
‱ Static analysis (often available in IDE, too!)
‱ Dynamic analysis
3. Enjoy the extra time you’ve freed up 
Copyright 2013 Coverity, Inc.

Weitere Àhnliche Inhalte

Was ist angesagt?

Test design techniques
Test design techniquesTest design techniques
Test design techniques
Mohamed Elshenawy
 
Severity & priority in software testing
Severity & priority in software testingSeverity & priority in software testing
Severity & priority in software testing
medsherb
 

Was ist angesagt? (20)

КАбЕРИНА АБЗЯбОВА - Getting ready for ISTQB Foundation 4.0: Overview and Q&A ...
КАбЕРИНА АБЗЯбОВА - Getting ready for ISTQB Foundation 4.0: Overview and Q&A ...КАбЕРИНА АБЗЯбОВА - Getting ready for ISTQB Foundation 4.0: Overview and Q&A ...
КАбЕРИНА АБЗЯбОВА - Getting ready for ISTQB Foundation 4.0: Overview and Q&A ...
 
Web application penetration testing lab setup guide
Web application penetration testing lab setup guideWeb application penetration testing lab setup guide
Web application penetration testing lab setup guide
 
Agile Test Driven Development
Agile Test Driven DevelopmentAgile Test Driven Development
Agile Test Driven Development
 
Robot Framework
Robot FrameworkRobot Framework
Robot Framework
 
Software Testing Process
Software Testing ProcessSoftware Testing Process
Software Testing Process
 
Test and Behaviour Driven Development (TDD/BDD)
Test and Behaviour Driven Development (TDD/BDD)Test and Behaviour Driven Development (TDD/BDD)
Test and Behaviour Driven Development (TDD/BDD)
 
Introduction to Robot Framework – Exove
Introduction to Robot Framework – ExoveIntroduction to Robot Framework – Exove
Introduction to Robot Framework – Exove
 
Test plan
Test planTest plan
Test plan
 
Test driven development with react
Test driven development with reactTest driven development with react
Test driven development with react
 
Code coverage
Code coverageCode coverage
Code coverage
 
Continuous testing
Continuous testing Continuous testing
Continuous testing
 
Code Coverage
Code CoverageCode Coverage
Code Coverage
 
Black & White Box testing
Black & White Box testingBlack & White Box testing
Black & White Box testing
 
Robot Framework Introduction
Robot Framework IntroductionRobot Framework Introduction
Robot Framework Introduction
 
PostmanêłŒ Newman을 읎용한 RestAPI 테슀튞 자동화 가읎드
PostmanêłŒ Newman을 읎용한 RestAPI 테슀튞 자동화 가읎드 PostmanêłŒ Newman을 읎용한 RestAPI 테슀튞 자동화 가읎드
PostmanêłŒ Newman을 읎용한 RestAPI 테슀튞 자동화 가읎드
 
defect tracking and management
defect tracking and management   defect tracking and management
defect tracking and management
 
Test design techniques
Test design techniquesTest design techniques
Test design techniques
 
Severity & priority in software testing
Severity & priority in software testingSeverity & priority in software testing
Severity & priority in software testing
 
Static Code Analysis
Static Code AnalysisStatic Code Analysis
Static Code Analysis
 
Difference between functional testing and non functional testing
Difference between functional testing and non functional testingDifference between functional testing and non functional testing
Difference between functional testing and non functional testing
 

Andere mochten auch

Making things that work with us - Distill
Making things that work with us - DistillMaking things that work with us - Distill
Making things that work with us - Distill
Matteo Collina
 
Making your washing machine talk with a power plant
Making your washing machine talk with a power plantMaking your washing machine talk with a power plant
Making your washing machine talk with a power plant
Matteo Collina
 
Detect Unknown Threats, Reduce Dwell Time, Accelerate Response
Detect Unknown Threats, Reduce Dwell Time, Accelerate ResponseDetect Unknown Threats, Reduce Dwell Time, Accelerate Response
Detect Unknown Threats, Reduce Dwell Time, Accelerate Response
Rahul Neel Mani
 
Empowerment Awareness
Empowerment AwarenessEmpowerment Awareness
Empowerment Awareness
altonbaird
 
Reasons for foreign listings by South African junior mining and exploration c...
Reasons for foreign listings by South African junior mining and exploration c...Reasons for foreign listings by South African junior mining and exploration c...
Reasons for foreign listings by South African junior mining and exploration c...
Vicki Shaw
 

Andere mochten auch (20)

Making things that work with us - Distill
Making things that work with us - DistillMaking things that work with us - Distill
Making things that work with us - Distill
 
Making your washing machine talk with a power plant
Making your washing machine talk with a power plantMaking your washing machine talk with a power plant
Making your washing machine talk with a power plant
 
Detect Unknown Threats, Reduce Dwell Time, Accelerate Response
Detect Unknown Threats, Reduce Dwell Time, Accelerate ResponseDetect Unknown Threats, Reduce Dwell Time, Accelerate Response
Detect Unknown Threats, Reduce Dwell Time, Accelerate Response
 
ABC of Infosec
ABC of InfosecABC of Infosec
ABC of Infosec
 
Sumit dhar
Sumit dharSumit dhar
Sumit dhar
 
Is Cyber Security the Elephant in the Boardroom?
Is Cyber Security the Elephant in the Boardroom? Is Cyber Security the Elephant in the Boardroom?
Is Cyber Security the Elephant in the Boardroom?
 
Daniel Avidor - Deciphering the Viral Code – The Secrets of Redmatch
Daniel Avidor - Deciphering the Viral Code – The Secrets of RedmatchDaniel Avidor - Deciphering the Viral Code – The Secrets of Redmatch
Daniel Avidor - Deciphering the Viral Code – The Secrets of Redmatch
 
Resume
ResumeResume
Resume
 
Presentacion departamentales
Presentacion departamentalesPresentacion departamentales
Presentacion departamentales
 
Ù…Ű±Ű§ŰŹŰčŰ© Ű§Ù„Ű”Ù Ű§Ù„Ű«Ű§Ù†Ù‰ Ű§Ù„Ű§ŰčŰŻŰ§ŰŻÙ‰
Ù…Ű±Ű§ŰŹŰčŰ© Ű§Ù„Ű”Ù Ű§Ù„Ű«Ű§Ù†Ù‰ Ű§Ù„Ű§ŰčŰŻŰ§ŰŻÙ‰Ù…Ű±Ű§ŰŹŰčŰ© Ű§Ù„Ű”Ù Ű§Ù„Ű«Ű§Ù†Ù‰ Ű§Ù„Ű§ŰčŰŻŰ§ŰŻÙ‰
Ù…Ű±Ű§ŰŹŰčŰ© Ű§Ù„Ű”Ù Ű§Ù„Ű«Ű§Ù†Ù‰ Ű§Ù„Ű§ŰčŰŻŰ§ŰŻÙ‰
 
Budget saving proposals - January 2014
Budget saving proposals - January 2014Budget saving proposals - January 2014
Budget saving proposals - January 2014
 
Happy Monthsary!
Happy Monthsary!Happy Monthsary!
Happy Monthsary!
 
TEDxSĂŁoPaulo - Institucional
TEDxSĂŁoPaulo - InstitucionalTEDxSĂŁoPaulo - Institucional
TEDxSĂŁoPaulo - Institucional
 
Trabajo de informatica aplicada #1
Trabajo de informatica aplicada #1Trabajo de informatica aplicada #1
Trabajo de informatica aplicada #1
 
Presentacion de economica politica
Presentacion de economica politicaPresentacion de economica politica
Presentacion de economica politica
 
Empowerment Awareness
Empowerment AwarenessEmpowerment Awareness
Empowerment Awareness
 
Android Market
Android MarketAndroid Market
Android Market
 
Reasons for foreign listings by South African junior mining and exploration c...
Reasons for foreign listings by South African junior mining and exploration c...Reasons for foreign listings by South African junior mining and exploration c...
Reasons for foreign listings by South African junior mining and exploration c...
 
Brighton & Hove budget cuts 2015-16
Brighton & Hove budget cuts 2015-16Brighton & Hove budget cuts 2015-16
Brighton & Hove budget cuts 2015-16
 
A replication study of the top performing systems in SemEval twitter sentimen...
A replication study of the top performing systems in SemEval twitter sentimen...A replication study of the top performing systems in SemEval twitter sentimen...
A replication study of the top performing systems in SemEval twitter sentimen...
 

Ähnlich wie Resource Leaks in Java

MC0078 SMU 2013 Fall session
MC0078 SMU 2013 Fall sessionMC0078 SMU 2013 Fall session
MC0078 SMU 2013 Fall session
Narinder Kumar
 
Dev buchan 30 proven tips
Dev buchan 30 proven tipsDev buchan 30 proven tips
Dev buchan 30 proven tips
Bill Buchan
 
Introduction to java exceptions
Introduction to java exceptionsIntroduction to java exceptions
Introduction to java exceptions
Sujit Kumar
 

Ähnlich wie Resource Leaks in Java (20)

Lecture 1 Try Throw Catch.pptx
Lecture 1 Try Throw Catch.pptxLecture 1 Try Throw Catch.pptx
Lecture 1 Try Throw Catch.pptx
 
Lecture 3.1.1 Try Throw Catch.pptx
Lecture 3.1.1 Try Throw Catch.pptxLecture 3.1.1 Try Throw Catch.pptx
Lecture 3.1.1 Try Throw Catch.pptx
 
Exception handling
Exception handlingException handling
Exception handling
 
Software Bugs A Software Architect Point Of View
Software Bugs    A Software Architect Point Of ViewSoftware Bugs    A Software Architect Point Of View
Software Bugs A Software Architect Point Of View
 
Lecture 20-21
Lecture 20-21Lecture 20-21
Lecture 20-21
 
Oracle real application clusters system tests with demo
Oracle real application clusters system tests with demoOracle real application clusters system tests with demo
Oracle real application clusters system tests with demo
 
Circuit breakers - Using Spring-Boot + Hystrix + Dashboard + Retry
Circuit breakers - Using Spring-Boot + Hystrix + Dashboard + RetryCircuit breakers - Using Spring-Boot + Hystrix + Dashboard + Retry
Circuit breakers - Using Spring-Boot + Hystrix + Dashboard + Retry
 
MC0078 SMU 2013 Fall session
MC0078 SMU 2013 Fall sessionMC0078 SMU 2013 Fall session
MC0078 SMU 2013 Fall session
 
Dev buchan 30 proven tips
Dev buchan 30 proven tipsDev buchan 30 proven tips
Dev buchan 30 proven tips
 
Metric Abuse: Frequently Misused Metrics in Oracle
Metric Abuse: Frequently Misused Metrics in OracleMetric Abuse: Frequently Misused Metrics in Oracle
Metric Abuse: Frequently Misused Metrics in Oracle
 
Java Exceptions and Exception Handling
 Java  Exceptions and Exception Handling Java  Exceptions and Exception Handling
Java Exceptions and Exception Handling
 
Exception handling
Exception handlingException handling
Exception handling
 
OSS Java Analysis - What You Might Be Missing
OSS Java Analysis - What You Might Be MissingOSS Java Analysis - What You Might Be Missing
OSS Java Analysis - What You Might Be Missing
 
lecture-c-corr-effkkkkkkkkkkkkkp (1).ppt
lecture-c-corr-effkkkkkkkkkkkkkp (1).pptlecture-c-corr-effkkkkkkkkkkkkkp (1).ppt
lecture-c-corr-effkkkkkkkkkkkkkp (1).ppt
 
We Make Debugging Sucks Less
We Make Debugging Sucks LessWe Make Debugging Sucks Less
We Make Debugging Sucks Less
 
Exception handling
Exception handlingException handling
Exception handling
 
How to fix bug or defects in software
How to fix bug or defects in software How to fix bug or defects in software
How to fix bug or defects in software
 
Making an Exception
Making an ExceptionMaking an Exception
Making an Exception
 
Introduction to java exceptions
Introduction to java exceptionsIntroduction to java exceptions
Introduction to java exceptions
 
Exception Handling Java
Exception Handling JavaException Handling Java
Exception Handling Java
 

Mehr von Coverity

The State of Software Quality
The State of Software QualityThe State of Software Quality
The State of Software Quality
Coverity
 
The Impact of a Medical Device Recall
The Impact of a Medical Device RecallThe Impact of a Medical Device Recall
The Impact of a Medical Device Recall
Coverity
 
Static Analysis Primer
Static Analysis PrimerStatic Analysis Primer
Static Analysis Primer
Coverity
 

Mehr von Coverity (8)

Finding Defects in C#: Coverity vs. FxCop
Finding Defects in C#: Coverity vs. FxCopFinding Defects in C#: Coverity vs. FxCop
Finding Defects in C#: Coverity vs. FxCop
 
Adopting Agile
Adopting AgileAdopting Agile
Adopting Agile
 
DevBeat 2013 - Developer-first Security
DevBeat 2013 - Developer-first SecurityDevBeat 2013 - Developer-first Security
DevBeat 2013 - Developer-first Security
 
The State of Software Quality
The State of Software QualityThe State of Software Quality
The State of Software Quality
 
The Impact of a Medical Device Recall
The Impact of a Medical Device RecallThe Impact of a Medical Device Recall
The Impact of a Medical Device Recall
 
Concurrency Errors in Java
Concurrency Errors in JavaConcurrency Errors in Java
Concurrency Errors in Java
 
The Psychology of C# Analysis
The Psychology of C# AnalysisThe Psychology of C# Analysis
The Psychology of C# Analysis
 
Static Analysis Primer
Static Analysis PrimerStatic Analysis Primer
Static Analysis Primer
 

KĂŒrzlich hochgeladen

KĂŒrzlich hochgeladen (20)

Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...
 
08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men
 
🐬 The future of MySQL is Postgres 🐘
🐬  The future of MySQL is Postgres   🐘🐬  The future of MySQL is Postgres   🐘
🐬 The future of MySQL is Postgres 🐘
 
08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men
 
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
 
Data Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonData Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt Robison
 
Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024
 
A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?
 
Factors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptxFactors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptx
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected Worker
 
Boost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityBoost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivity
 
What Are The Drone Anti-jamming Systems Technology?
What Are The Drone Anti-jamming Systems Technology?What Are The Drone Anti-jamming Systems Technology?
What Are The Drone Anti-jamming Systems Technology?
 
[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf
 
Exploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone ProcessorsExploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone Processors
 
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
 
Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024
 
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
 
Slack Application Development 101 Slides
Slack Application Development 101 SlidesSlack Application Development 101 Slides
Slack Application Development 101 Slides
 
Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024
 
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
 

Resource Leaks in Java

  • 2. What Is a Resource Leak? And Why You Should Care About Them
  • 3. What Is a Resource Leak? A resource leak is an erroneous pattern of resource consumption where a program does not release resources it has acquired. Typical resource leaks include memory leaks and handle leaks.
  • 4. Why You Should Care Consequences to users: ‱ Poor performance ‱ Poor stability or reliability ‱ Denial of service Consequences to developers: ‱ Time consuming to find, even with a debugger ‱ Can reduce reliability of the testing suite by interrupting test runs
  • 5. Question: Java is a modern language with a garbage collector to take care of resource management. Doesn’t that mean that I don’t need to worry about resource leaks?
  • 6. Answer: No! The garbage collector (GC) can help ensure unused objects on the heap are reclaimed when they are no longer used. But: ‱ It can't guarantee that you will have the resources you need, when you need them ‱ Reference subtleties can “trick” the GC into leaving unexpected objects on the heap ‱ Many objects, such as database connections and file handles, are managed by the operating system - not Java
  • 7. Consider This Code Snippet* Note: ‱ It tries to handle exceptions while shutting down the database ‱ It creates Connection and Statement objects on lines 43 and 44 ‱ This method is associated with a task and may run repeatedly * From an open source project
  • 8. Best Case: 1. L43: “con” allocated, connected to db. 2. L44: statement created, “SHUTDOWN” executed 3. Assuming no exceptions occur, the method exits 4. Eventually, the GC detects that the handles are no longer used and schedule calls to their finalizers 5. In a later pass, the finalizers will be called, releasing the underlying handles 6. All is good
  • 9. Reality: 1. L43: “con” allocated, connected to db. 2. L44: statement created, “SHUTDOWN” executed 3. Assuming no exceptions occur, the method exits 4. The application continues to work with the database in other methods 5. Eventually, other methods are unable to get new statement handles and fail 6. The GC never gets to detect that the handles are no longer used, or scheduled calls to their finalizers never get run
  • 10. To Avoid the Problem: Explicitly close the handles Replace lines 43 and 44 with something like the following code: Connection con = null; Statement stmt = null; try { con = DriverManager.getConnection(<url>); stmt = con.createStatement(); stmt.execute("SHUTDOWN"); // Perhaps some catch blocks for SQLException, etc. } finally { // if you’re paranoid, put these in a separate try/catch for SQLException if (stmt != null) { stmt.close(); } if (con != null) { con.close(); } } Note that Java 7 has a simplified “try-with-resources” statement.
  • 11. In Short
 1. Remain vigilant about resource usage ‱ Explicitly close resources when you are done with them ‱ Be careful to handle exceptional cases, too! 2. Use tools to identify cases that you miss ‱ Static analysis (often available in IDE, too!) ‱ Dynamic analysis 3. Enjoy the extra time you’ve freed up 