SlideShare uma empresa Scribd logo
1 de 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.

Mais conteúdo relacionado

Mais procurados

DCSF19 Dockerfile Best Practices
DCSF19 Dockerfile Best PracticesDCSF19 Dockerfile Best Practices
DCSF19 Dockerfile Best PracticesDocker, Inc.
 
Distributed Storage with IPFS and Python!
Distributed Storage with IPFS and Python!Distributed Storage with IPFS and Python!
Distributed Storage with IPFS and Python!Abhinav Srivastava
 
Frida Android run time hooking - Bhargav Gajera & Vitthal Shinde
Frida  Android run time hooking - Bhargav Gajera & Vitthal ShindeFrida  Android run time hooking - Bhargav Gajera & Vitthal Shinde
Frida Android run time hooking - Bhargav Gajera & Vitthal ShindeNSConclave
 
Finding Your Way in Container Security
Finding Your Way in Container SecurityFinding Your Way in Container Security
Finding Your Way in Container SecurityKsenia Peguero
 
How to successfully grow a code review culture
How to successfully grow a code review cultureHow to successfully grow a code review culture
How to successfully grow a code review cultureNina Zakharenko
 
Java Performance Analysis on Linux with Flame Graphs
Java Performance Analysis on Linux with Flame GraphsJava Performance Analysis on Linux with Flame Graphs
Java Performance Analysis on Linux with Flame GraphsBrendan Gregg
 
Presentation of framework Angular
Presentation of framework AngularPresentation of framework Angular
Presentation of framework AngularLhouceine OUHAMZA
 
Introduction à l’intégration continue avec Jenkins
Introduction à l’intégration continue avec JenkinsIntroduction à l’intégration continue avec Jenkins
Introduction à l’intégration continue avec JenkinsEric Hogue
 
nginx 입문 공부자료
nginx 입문 공부자료nginx 입문 공부자료
nginx 입문 공부자료choi sungwook
 
Visualizing Systems with Statemaps
Visualizing Systems with StatemapsVisualizing Systems with Statemaps
Visualizing Systems with Statemapsbcantrill
 
Tuning kafka pipelines
Tuning kafka pipelinesTuning kafka pipelines
Tuning kafka pipelinesSumant Tambe
 
containerd the universal container runtime
containerd the universal container runtimecontainerd the universal container runtime
containerd the universal container runtimeDocker, Inc.
 
Quickboot on i.MX6
Quickboot on i.MX6Quickboot on i.MX6
Quickboot on i.MX6Gary Bisson
 
Kafka Tutorial: Kafka Security
Kafka Tutorial: Kafka SecurityKafka Tutorial: Kafka Security
Kafka Tutorial: Kafka SecurityJean-Paul Azar
 
[DockerCon 2023] Reproducible builds with BuildKit for software supply chain ...
[DockerCon 2023] Reproducible builds with BuildKit for software supply chain ...[DockerCon 2023] Reproducible builds with BuildKit for software supply chain ...
[DockerCon 2023] Reproducible builds with BuildKit for software supply chain ...Akihiro Suda
 

Mais procurados (20)

Vagrant
VagrantVagrant
Vagrant
 
DCSF19 Dockerfile Best Practices
DCSF19 Dockerfile Best PracticesDCSF19 Dockerfile Best Practices
DCSF19 Dockerfile Best Practices
 
Distributed Storage with IPFS and Python!
Distributed Storage with IPFS and Python!Distributed Storage with IPFS and Python!
Distributed Storage with IPFS and Python!
 
Frida Android run time hooking - Bhargav Gajera & Vitthal Shinde
Frida  Android run time hooking - Bhargav Gajera & Vitthal ShindeFrida  Android run time hooking - Bhargav Gajera & Vitthal Shinde
Frida Android run time hooking - Bhargav Gajera & Vitthal Shinde
 
Finding Your Way in Container Security
Finding Your Way in Container SecurityFinding Your Way in Container Security
Finding Your Way in Container Security
 
Git Flow y GitOps
Git Flow y GitOpsGit Flow y GitOps
Git Flow y GitOps
 
How to successfully grow a code review culture
How to successfully grow a code review cultureHow to successfully grow a code review culture
How to successfully grow a code review culture
 
Java Performance Analysis on Linux with Flame Graphs
Java Performance Analysis on Linux with Flame GraphsJava Performance Analysis on Linux with Flame Graphs
Java Performance Analysis on Linux with Flame Graphs
 
Bucardo
BucardoBucardo
Bucardo
 
Presentation of framework Angular
Presentation of framework AngularPresentation of framework Angular
Presentation of framework Angular
 
Scrum course
Scrum courseScrum course
Scrum course
 
Introduction à l’intégration continue avec Jenkins
Introduction à l’intégration continue avec JenkinsIntroduction à l’intégration continue avec Jenkins
Introduction à l’intégration continue avec Jenkins
 
nginx 입문 공부자료
nginx 입문 공부자료nginx 입문 공부자료
nginx 입문 공부자료
 
Visualizing Systems with Statemaps
Visualizing Systems with StatemapsVisualizing Systems with Statemaps
Visualizing Systems with Statemaps
 
Tuning kafka pipelines
Tuning kafka pipelinesTuning kafka pipelines
Tuning kafka pipelines
 
Go Language presentation
Go Language presentationGo Language presentation
Go Language presentation
 
containerd the universal container runtime
containerd the universal container runtimecontainerd the universal container runtime
containerd the universal container runtime
 
Quickboot on i.MX6
Quickboot on i.MX6Quickboot on i.MX6
Quickboot on i.MX6
 
Kafka Tutorial: Kafka Security
Kafka Tutorial: Kafka SecurityKafka Tutorial: Kafka Security
Kafka Tutorial: Kafka Security
 
[DockerCon 2023] Reproducible builds with BuildKit for software supply chain ...
[DockerCon 2023] Reproducible builds with BuildKit for software supply chain ...[DockerCon 2023] Reproducible builds with BuildKit for software supply chain ...
[DockerCon 2023] Reproducible builds with BuildKit for software supply chain ...
 

Destaque

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
 
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
 

Destaque (19)

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
 
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...
 

Semelhante a 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
 

Semelhante a 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
 

Mais de 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
 

Mais de 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
 

Último

DEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
DEV meet-up UiPath Document Understanding May 7 2024 AmsterdamDEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
DEV meet-up UiPath Document Understanding May 7 2024 AmsterdamUiPathCommunity
 
AWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of TerraformAWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of TerraformAndrey Devyatkin
 
CNIC Information System with Pakdata Cf In Pakistan
CNIC Information System with Pakdata Cf In PakistanCNIC Information System with Pakdata Cf In Pakistan
CNIC Information System with Pakdata Cf In Pakistandanishmna97
 
MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024MIND CTI
 
Architecting Cloud Native Applications
Architecting Cloud Native ApplicationsArchitecting Cloud Native Applications
Architecting Cloud Native ApplicationsWSO2
 
Cyberprint. Dark Pink Apt Group [EN].pdf
Cyberprint. Dark Pink Apt Group [EN].pdfCyberprint. Dark Pink Apt Group [EN].pdf
Cyberprint. Dark Pink Apt Group [EN].pdfOverkill Security
 
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data DiscoveryTrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data DiscoveryTrustArc
 
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost SavingRepurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost SavingEdi Saputra
 
Why Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businessWhy Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businesspanagenda
 
2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...Martijn de Jong
 
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...apidays
 
"I see eyes in my soup": How Delivery Hero implemented the safety system for ...
"I see eyes in my soup": How Delivery Hero implemented the safety system for ..."I see eyes in my soup": How Delivery Hero implemented the safety system for ...
"I see eyes in my soup": How Delivery Hero implemented the safety system for ...Zilliz
 
Exploring Multimodal Embeddings with Milvus
Exploring Multimodal Embeddings with MilvusExploring Multimodal Embeddings with Milvus
Exploring Multimodal Embeddings with MilvusZilliz
 
DBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor PresentationDBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor PresentationDropbox
 
Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...
Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...
Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...apidays
 
Strategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherStrategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherRemote DBA Services
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FMESafe Software
 
FWD Group - Insurer Innovation Award 2024
FWD Group - Insurer Innovation Award 2024FWD Group - Insurer Innovation Award 2024
FWD Group - Insurer Innovation Award 2024The Digital Insurer
 
ICT role in 21st century education and its challenges
ICT role in 21st century education and its challengesICT role in 21st century education and its challenges
ICT role in 21st century education and its challengesrafiqahmad00786416
 
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot TakeoffStrategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoffsammart93
 

Último (20)

DEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
DEV meet-up UiPath Document Understanding May 7 2024 AmsterdamDEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
DEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
 
AWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of TerraformAWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of Terraform
 
CNIC Information System with Pakdata Cf In Pakistan
CNIC Information System with Pakdata Cf In PakistanCNIC Information System with Pakdata Cf In Pakistan
CNIC Information System with Pakdata Cf In Pakistan
 
MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024
 
Architecting Cloud Native Applications
Architecting Cloud Native ApplicationsArchitecting Cloud Native Applications
Architecting Cloud Native Applications
 
Cyberprint. Dark Pink Apt Group [EN].pdf
Cyberprint. Dark Pink Apt Group [EN].pdfCyberprint. Dark Pink Apt Group [EN].pdf
Cyberprint. Dark Pink Apt Group [EN].pdf
 
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data DiscoveryTrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
 
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost SavingRepurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
 
Why Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businessWhy Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire business
 
2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...
 
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
 
"I see eyes in my soup": How Delivery Hero implemented the safety system for ...
"I see eyes in my soup": How Delivery Hero implemented the safety system for ..."I see eyes in my soup": How Delivery Hero implemented the safety system for ...
"I see eyes in my soup": How Delivery Hero implemented the safety system for ...
 
Exploring Multimodal Embeddings with Milvus
Exploring Multimodal Embeddings with MilvusExploring Multimodal Embeddings with Milvus
Exploring Multimodal Embeddings with Milvus
 
DBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor PresentationDBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor Presentation
 
Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...
Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...
Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...
 
Strategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherStrategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a Fresher
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
 
FWD Group - Insurer Innovation Award 2024
FWD Group - Insurer Innovation Award 2024FWD Group - Insurer Innovation Award 2024
FWD Group - Insurer Innovation Award 2024
 
ICT role in 21st century education and its challenges
ICT role in 21st century education and its challengesICT role in 21st century education and its challenges
ICT role in 21st century education and its challenges
 
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot TakeoffStrategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
 

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 