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?

Deadlock management
Deadlock managementDeadlock management
Deadlock managementAhmed kasim
 
Unit three Advanced State Modelling
Unit three Advanced State ModellingUnit three Advanced State Modelling
Unit three Advanced State ModellingDr Chetan Shelke
 
Waterfall Model (Software Engineering)
Waterfall Model (Software Engineering)  Waterfall Model (Software Engineering)
Waterfall Model (Software Engineering) MuhammadTalha436
 
Angular data binding
Angular data binding Angular data binding
Angular data binding Sultan Ahmed
 
Spm unit iii-risk-working in teams
Spm unit iii-risk-working in teamsSpm unit iii-risk-working in teams
Spm unit iii-risk-working in teamsKanchana Devi
 
Dynamic storage allocation techniques in Compiler design
Dynamic storage allocation techniques in Compiler designDynamic storage allocation techniques in Compiler design
Dynamic storage allocation techniques in Compiler designkunjan shah
 
Command Design Pattern
Command Design Pattern Command Design Pattern
Command Design Pattern anil kanzariya
 
deadlock detection using Goldman's algorithm by ANIKET CHOUDHURY
deadlock detection using Goldman's algorithm by ANIKET CHOUDHURYdeadlock detection using Goldman's algorithm by ANIKET CHOUDHURY
deadlock detection using Goldman's algorithm by ANIKET CHOUDHURYअनिकेत चौधरी
 
Operating system notes
Operating system notesOperating system notes
Operating system notesSANTOSH RATH
 
MC 7204 OS Question Bank with Answer
MC 7204 OS Question Bank with AnswerMC 7204 OS Question Bank with Answer
MC 7204 OS Question Bank with Answersellappasiva
 
Spring Framework Tutorial | Spring Tutorial For Beginners With Examples | Jav...
Spring Framework Tutorial | Spring Tutorial For Beginners With Examples | Jav...Spring Framework Tutorial | Spring Tutorial For Beginners With Examples | Jav...
Spring Framework Tutorial | Spring Tutorial For Beginners With Examples | Jav...Edureka!
 
Deadlock detection & prevention
Deadlock detection & preventionDeadlock detection & prevention
Deadlock detection & preventionIkhtiarUddinShaHin
 
Loc and function point
Loc and function pointLoc and function point
Loc and function pointMitali Chugh
 

Was ist angesagt? (20)

Deadlock management
Deadlock managementDeadlock management
Deadlock management
 
Unit three Advanced State Modelling
Unit three Advanced State ModellingUnit three Advanced State Modelling
Unit three Advanced State Modelling
 
Angular Basics.pptx
Angular Basics.pptxAngular Basics.pptx
Angular Basics.pptx
 
Waterfall Model (Software Engineering)
Waterfall Model (Software Engineering)  Waterfall Model (Software Engineering)
Waterfall Model (Software Engineering)
 
Angular data binding
Angular data binding Angular data binding
Angular data binding
 
Spm unit iii-risk-working in teams
Spm unit iii-risk-working in teamsSpm unit iii-risk-working in teams
Spm unit iii-risk-working in teams
 
Dynamic storage allocation techniques in Compiler design
Dynamic storage allocation techniques in Compiler designDynamic storage allocation techniques in Compiler design
Dynamic storage allocation techniques in Compiler design
 
Command Design Pattern
Command Design Pattern Command Design Pattern
Command Design Pattern
 
Flyweight Pattern
Flyweight PatternFlyweight Pattern
Flyweight Pattern
 
deadlock detection using Goldman's algorithm by ANIKET CHOUDHURY
deadlock detection using Goldman's algorithm by ANIKET CHOUDHURYdeadlock detection using Goldman's algorithm by ANIKET CHOUDHURY
deadlock detection using Goldman's algorithm by ANIKET CHOUDHURY
 
Temporal database
Temporal databaseTemporal database
Temporal database
 
Deadlock dbms
Deadlock dbmsDeadlock dbms
Deadlock dbms
 
Training On Angular Js
Training On Angular JsTraining On Angular Js
Training On Angular Js
 
Model View Controller (MVC)
Model View Controller (MVC)Model View Controller (MVC)
Model View Controller (MVC)
 
Operating system notes
Operating system notesOperating system notes
Operating system notes
 
MC 7204 OS Question Bank with Answer
MC 7204 OS Question Bank with AnswerMC 7204 OS Question Bank with Answer
MC 7204 OS Question Bank with Answer
 
Spring Framework Tutorial | Spring Tutorial For Beginners With Examples | Jav...
Spring Framework Tutorial | Spring Tutorial For Beginners With Examples | Jav...Spring Framework Tutorial | Spring Tutorial For Beginners With Examples | Jav...
Spring Framework Tutorial | Spring Tutorial For Beginners With Examples | Jav...
 
Django in the Real World
Django in the Real WorldDjango in the Real World
Django in the Real World
 
Deadlock detection & prevention
Deadlock detection & preventionDeadlock detection & prevention
Deadlock detection & prevention
 
Loc and function point
Loc and function pointLoc and function point
Loc and function point
 

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 - DistillMatteo 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 plantMatteo 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 ResponseRahul Neel Mani
 
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? Rahul Neel Mani
 
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 RedmatchMIT Forum of Israel
 
مراجعة الصف الثانى الاعدادى
مراجعة الصف الثانى الاعدادىمراجعة الصف الثانى الاعدادى
مراجعة الصف الثانى الاعدادىHanaa Ahmed
 
TEDxSãoPaulo - Institucional
TEDxSãoPaulo - InstitucionalTEDxSãoPaulo - Institucional
TEDxSãoPaulo - InstitucionalMonkeyBusiness
 
Trabajo de informatica aplicada #1
Trabajo de informatica aplicada #1Trabajo de informatica aplicada #1
Trabajo de informatica aplicada #1Rolando Carrera
 
Presentacion de economica politica
Presentacion de economica politicaPresentacion de economica politica
Presentacion de economica politicaabelardoac
 
Empowerment Awareness
Empowerment AwarenessEmpowerment Awareness
Empowerment Awarenessaltonbaird
 
Android Market
Android MarketAndroid Market
Android MarketTeo Romera
 
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
 
Brighton & Hove budget cuts 2015-16
Brighton & Hove budget cuts 2015-16Brighton & Hove budget cuts 2015-16
Brighton & Hove budget cuts 2015-16brightonpa
 
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...Raphael Troncy
 

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

Lecture 1 Try Throw Catch.pptx
Lecture 1 Try Throw Catch.pptxLecture 1 Try Throw Catch.pptx
Lecture 1 Try Throw Catch.pptxVishuSaini22
 
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.pptxsunilsoni446112
 
Exception handling
Exception handlingException handling
Exception handlingpooja kumari
 
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 ViewShahzad
 
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 demoAjith Narayanan
 
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 + RetryBruno Henrique Rother
 
MC0078 SMU 2013 Fall session
MC0078 SMU 2013 Fall sessionMC0078 SMU 2013 Fall session
MC0078 SMU 2013 Fall sessionNarinder Kumar
 
Dev buchan 30 proven tips
Dev buchan 30 proven tipsDev buchan 30 proven tips
Dev buchan 30 proven tipsBill Buchan
 
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 OracleSteve Karam
 
Java Exceptions and Exception Handling
 Java  Exceptions and Exception Handling Java  Exceptions and Exception Handling
Java Exceptions and Exception HandlingMaqdamYasir
 
Exception handling
Exception handlingException handling
Exception handlingMinal Maniar
 
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 MissingCoverity
 
lecture-c-corr-effkkkkkkkkkkkkkp (1).ppt
lecture-c-corr-effkkkkkkkkkkkkkp (1).pptlecture-c-corr-effkkkkkkkkkkkkkp (1).ppt
lecture-c-corr-effkkkkkkkkkkkkkp (1).pptZeeshanAli593762
 
We Make Debugging Sucks Less
We Make Debugging Sucks LessWe Make Debugging Sucks Less
We Make Debugging Sucks LessAlon Fliess
 
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 Rajasekar Subramanian
 
Introduction to java exceptions
Introduction to java exceptionsIntroduction to java exceptions
Introduction to java exceptionsSujit Kumar
 
Exception Handling Java
Exception Handling JavaException Handling Java
Exception Handling Javaankitgarg_er
 

Ä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

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. FxCopCoverity
 
Adopting Agile
Adopting AgileAdopting Agile
Adopting AgileCoverity
 
DevBeat 2013 - Developer-first Security
DevBeat 2013 - Developer-first SecurityDevBeat 2013 - Developer-first Security
DevBeat 2013 - Developer-first SecurityCoverity
 
The State of Software Quality
The State of Software QualityThe State of Software Quality
The State of Software QualityCoverity
 
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 RecallCoverity
 
Concurrency Errors in Java
Concurrency Errors in JavaConcurrency Errors in Java
Concurrency Errors in JavaCoverity
 
The Psychology of C# Analysis
The Psychology of C# AnalysisThe Psychology of C# Analysis
The Psychology of C# AnalysisCoverity
 
Static Analysis Primer
Static Analysis PrimerStatic Analysis Primer
Static Analysis PrimerCoverity
 

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

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...apidays
 
The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024Rafal Los
 
Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)Allon Mureinik
 
Salesforce Community Group Quito, Salesforce 101
Salesforce Community Group Quito, Salesforce 101Salesforce Community Group Quito, Salesforce 101
Salesforce Community Group Quito, Salesforce 101Paola De la Torre
 
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 MenDelhi Call girls
 
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Miguel Araújo
 
Top 5 Benefits OF Using Muvi Live Paywall For Live Streams
Top 5 Benefits OF Using Muvi Live Paywall For Live StreamsTop 5 Benefits OF Using Muvi Live Paywall For Live Streams
Top 5 Benefits OF Using Muvi Live Paywall For Live StreamsRoshan Dwivedi
 
GenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationGenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationMichael W. Hawkins
 
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 Processorsdebabhi2
 
Scaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationScaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationRadu Cotescu
 
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure serviceWhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure servicePooja Nehwal
 
Unblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen FramesUnblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen FramesSinan KOZAK
 
Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024The Digital Insurer
 
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 productivityPrincipled Technologies
 
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking MenDelhi Call girls
 
Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...
Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...
Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...gurkirankumar98700
 
Automating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps ScriptAutomating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps Scriptwesley chun
 
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 DevelopmentsTrustArc
 
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdfThe Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdfEnterprise Knowledge
 
Developing An App To Navigate The Roads of Brazil
Developing An App To Navigate The Roads of BrazilDeveloping An App To Navigate The Roads of Brazil
Developing An App To Navigate The Roads of BrazilV3cube
 

Kürzlich hochgeladen (20)

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...
 
The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024
 
Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)
 
Salesforce Community Group Quito, Salesforce 101
Salesforce Community Group Quito, Salesforce 101Salesforce Community Group Quito, Salesforce 101
Salesforce Community Group Quito, Salesforce 101
 
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
 
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
 
Top 5 Benefits OF Using Muvi Live Paywall For Live Streams
Top 5 Benefits OF Using Muvi Live Paywall For Live StreamsTop 5 Benefits OF Using Muvi Live Paywall For Live Streams
Top 5 Benefits OF Using Muvi Live Paywall For Live Streams
 
GenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationGenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day Presentation
 
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
 
Scaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationScaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organization
 
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure serviceWhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
 
Unblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen FramesUnblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen Frames
 
Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024
 
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
 
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
 
Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...
Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...
Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...
 
Automating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps ScriptAutomating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps Script
 
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
 
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdfThe Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
 
Developing An App To Navigate The Roads of Brazil
Developing An App To Navigate The Roads of BrazilDeveloping An App To Navigate The Roads of Brazil
Developing An App To Navigate The Roads of Brazil
 

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 