SlideShare une entreprise Scribd logo
1  sur  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.

Contenu connexe

Tendances

Oracle R12 EBS Performance Tuning
Oracle R12 EBS Performance TuningOracle R12 EBS Performance Tuning
Oracle R12 EBS Performance TuningScott Jenner
 
Getting optimal performance from oracle e-business suite presentation
Getting optimal performance from oracle e-business suite presentationGetting optimal performance from oracle e-business suite presentation
Getting optimal performance from oracle e-business suite presentationBerry Clemens
 
Oracle Performance Tuning Fundamentals
Oracle Performance Tuning FundamentalsOracle Performance Tuning Fundamentals
Oracle Performance Tuning FundamentalsEnkitec
 
Oracle db performance tuning
Oracle db performance tuningOracle db performance tuning
Oracle db performance tuningSimon Huang
 
NoSQL databases - An introduction
NoSQL databases - An introductionNoSQL databases - An introduction
NoSQL databases - An introductionPooyan Mehrparvar
 
EM12c: Capacity Planning with OEM Metrics
EM12c: Capacity Planning with OEM MetricsEM12c: Capacity Planning with OEM Metrics
EM12c: Capacity Planning with OEM MetricsMaaz Anjum
 
SQL Server Cluster Presentation
SQL Server Cluster PresentationSQL Server Cluster Presentation
SQL Server Cluster Presentationwebhostingguy
 
Less01 architecture
Less01 architectureLess01 architecture
Less01 architectureAmit Bhalla
 
Apache Hadoop YARN: Understanding the Data Operating System of Hadoop
Apache Hadoop YARN: Understanding the Data Operating System of HadoopApache Hadoop YARN: Understanding the Data Operating System of Hadoop
Apache Hadoop YARN: Understanding the Data Operating System of HadoopHortonworks
 
Data Modeling in Looker
Data Modeling in LookerData Modeling in Looker
Data Modeling in LookerLooker
 
Module 2 - Datalake
Module 2 - DatalakeModule 2 - Datalake
Module 2 - DatalakeLam Le
 
Event-driven serverless functions with Next.js and Inngest
Event-driven serverless functions with Next.js and InngestEvent-driven serverless functions with Next.js and Inngest
Event-driven serverless functions with Next.js and InngestDan Farrelly
 
Microsoft SQL Server internals & architecture
Microsoft SQL Server internals & architectureMicrosoft SQL Server internals & architecture
Microsoft SQL Server internals & architectureKevin Kline
 
Introduction to Databases - query optimizations for MySQL
Introduction to Databases - query optimizations for MySQLIntroduction to Databases - query optimizations for MySQL
Introduction to Databases - query optimizations for MySQLMárton Kodok
 

Tendances (20)

Oracle R12 EBS Performance Tuning
Oracle R12 EBS Performance TuningOracle R12 EBS Performance Tuning
Oracle R12 EBS Performance Tuning
 
Migrating Oracle to PostgreSQL
Migrating Oracle to PostgreSQLMigrating Oracle to PostgreSQL
Migrating Oracle to PostgreSQL
 
Getting optimal performance from oracle e-business suite presentation
Getting optimal performance from oracle e-business suite presentationGetting optimal performance from oracle e-business suite presentation
Getting optimal performance from oracle e-business suite presentation
 
Oracle Performance Tuning Fundamentals
Oracle Performance Tuning FundamentalsOracle Performance Tuning Fundamentals
Oracle Performance Tuning Fundamentals
 
Defect Causal Analysis
Defect Causal Analysis Defect Causal Analysis
Defect Causal Analysis
 
Oracle db performance tuning
Oracle db performance tuningOracle db performance tuning
Oracle db performance tuning
 
NoSQL databases - An introduction
NoSQL databases - An introductionNoSQL databases - An introduction
NoSQL databases - An introduction
 
dbt 101
dbt 101dbt 101
dbt 101
 
EM12c: Capacity Planning with OEM Metrics
EM12c: Capacity Planning with OEM MetricsEM12c: Capacity Planning with OEM Metrics
EM12c: Capacity Planning with OEM Metrics
 
SQL Server Cluster Presentation
SQL Server Cluster PresentationSQL Server Cluster Presentation
SQL Server Cluster Presentation
 
Sistema de gestores de base de datos
Sistema de gestores de base de datosSistema de gestores de base de datos
Sistema de gestores de base de datos
 
Less01 architecture
Less01 architectureLess01 architecture
Less01 architecture
 
Apache Hadoop YARN: Understanding the Data Operating System of Hadoop
Apache Hadoop YARN: Understanding the Data Operating System of HadoopApache Hadoop YARN: Understanding the Data Operating System of Hadoop
Apache Hadoop YARN: Understanding the Data Operating System of Hadoop
 
Cursors.ppt
Cursors.pptCursors.ppt
Cursors.ppt
 
Data Modeling in Looker
Data Modeling in LookerData Modeling in Looker
Data Modeling in Looker
 
Module 2 - Datalake
Module 2 - DatalakeModule 2 - Datalake
Module 2 - Datalake
 
Event-driven serverless functions with Next.js and Inngest
Event-driven serverless functions with Next.js and InngestEvent-driven serverless functions with Next.js and Inngest
Event-driven serverless functions with Next.js and Inngest
 
Oracle database introduction
Oracle database introductionOracle database introduction
Oracle database introduction
 
Microsoft SQL Server internals & architecture
Microsoft SQL Server internals & architectureMicrosoft SQL Server internals & architecture
Microsoft SQL Server internals & architecture
 
Introduction to Databases - query optimizations for MySQL
Introduction to Databases - query optimizations for MySQLIntroduction to Databases - query optimizations for MySQL
Introduction to Databases - query optimizations for MySQL
 

En vedette

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
 

En vedette (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...
 

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

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

Plus 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
 

Plus 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
 

Dernier

Presentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreterPresentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreternaman860154
 
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProduct Anonymous
 
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
 
CNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of ServiceCNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of Servicegiselly40
 
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...Enterprise Knowledge
 
Evaluating the top large language models.pdf
Evaluating the top large language models.pdfEvaluating the top large language models.pdf
Evaluating the top large language models.pdfChristopherTHyatt
 
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 WorkerThousandEyes
 
[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.pdfhans926745
 
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?Antenna Manufacturer Coco
 
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptxHampshireHUG
 
A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)Gabriella Davis
 
GenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationGenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationMichael W. Hawkins
 
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...Neo4j
 
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 MenDelhi Call girls
 
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
 
GenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdfGenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdflior mazor
 
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
 
Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)wesley chun
 
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 WorkerThousandEyes
 
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...Igalia
 

Dernier (20)

Presentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreterPresentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreter
 
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
 
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
 
CNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of ServiceCNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of Service
 
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...
 
Evaluating the top large language models.pdf
Evaluating the top large language models.pdfEvaluating the top large language models.pdf
Evaluating the top large language models.pdf
 
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
 
[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
 
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?
 
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
 
A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)
 
GenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationGenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day Presentation
 
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
 
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
 
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
 
GenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdfGenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdf
 
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
 
Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)
 
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
 
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
 

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 