Using Try-With-Resources to Prevent Memory Leaks in Java

Опубликовано: 18 Май 2026
на канале: Merlin Wellington
178
8

Contrary to popular belief, you can have memory leaks in Java. Often, they are the result of objects that use system resources not being closed properly. Java gives us a few strategies for making sure that those kinds of objects always get closed.

In this video I'll walk you through:
How these types of memory leaks occur
Using Try/Catch/Finally to fix the problem
Using Try-with-Resources to fix the problem

TIMESTAMPS
0:00 Introduction
0:30 An example where a Scanner never gets closed
0:56 Ensuring closure using try/catch/finally
1:22 Ensuring closure using try-with-resources
2:06 Making our own auto-closeable classes
2:50 Multiple auto-closeable objects
3:37 Using Final objects created elsewhere

ABOUT MY CHANNEL
My channel is about good software engineering practices. We cover introductions to programming in C and Java. But I also have lots of software and computer engineering topics like PIC programming, advanced programming techniques, and things that distinguish good code from code that works.

Check out my channel here:
   / @wizardcraftcode  

Don’t forget to subscribe!

CHECK OUT MY OTHER VIDEOS:

C Programming Playlist:    • Coding in C  
Intro to Java Playlist:    • Introduction to Java Programming based on ...  
Software Engineering Topics Playlist:    • General Software Engineering Topics