Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java Disposable pattern

C# supports disposable pattern for deterministic garbage collection using the dispose pattern.

Is there such pattern for java?

Java 7 has autoclosable, which you can use with try finally blocks to invoke the close method.

What about versions prior to 7?

Is there a disposable pattern (deterministic garbage collection) for Java 5 or 6?

like image 603
DarthVader Avatar asked Oct 14 '11 21:10

DarthVader


2 Answers

The entire purpose of the disposal pattern is to support C#'s unique using (temporaryObject) pattern. Java has had nothing like that pattern before 7.

All Java objects that had resources supported the disposal pattern via manually closing the object that held resources.

like image 27
Randolpho Avatar answered Sep 27 '22 19:09

Randolpho


The closest prior to Java 7 is just "manual" try/finally blocks:

FileInputStream input = new FileInputStream(...);
try {
  // Use input
} finally {
  input.close();
}

The using statement was one of the things I found nicest about C# when I first started using C# 1.0 from a Java background. It's good to see it finally in Java 7 :)

You should also consider Closeables in Guava - it allows you to not worry about whether or not a reference is null (just like a using statement does) and optionally "logs and swallows" exceptions thrown when closing, to avoid any such exception from effectively "overwriting" an exception thrown from the try block.

like image 187
Jon Skeet Avatar answered Sep 27 '22 18:09

Jon Skeet