2015-09-07 11:44:36 -06:00
|
|
|
// exceptions/CleanupIdiom.java
|
2020-10-07 13:35:40 -06:00
|
|
|
// (c)2020 MindView LLC: see Copyright.txt
|
2015-11-15 15:51:35 -08:00
|
|
|
// We make no guarantees that this code is fit for any purpose.
|
2016-09-23 13:23:35 -06:00
|
|
|
// Visit http://OnJava8.com for more book information.
|
2016-01-25 18:05:55 -08:00
|
|
|
// Disposable objects must be followed by a try-finally
|
2015-06-15 17:47:35 -07:00
|
|
|
|
|
|
|
class NeedsCleanup { // Construction can't fail
|
|
|
|
private static long counter = 1;
|
|
|
|
private final long id = counter++;
|
|
|
|
public void dispose() {
|
2015-12-15 11:47:04 -08:00
|
|
|
System.out.println(
|
|
|
|
"NeedsCleanup " + id + " disposed");
|
2015-06-15 17:47:35 -07:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
class ConstructionException extends Exception {}
|
|
|
|
|
|
|
|
class NeedsCleanup2 extends NeedsCleanup {
|
|
|
|
// Construction can fail:
|
2017-05-01 14:33:10 -06:00
|
|
|
NeedsCleanup2() throws ConstructionException {}
|
2015-06-15 17:47:35 -07:00
|
|
|
}
|
|
|
|
|
|
|
|
public class CleanupIdiom {
|
|
|
|
public static void main(String[] args) {
|
2016-11-21 12:37:57 -08:00
|
|
|
// [1]:
|
2015-06-15 17:47:35 -07:00
|
|
|
NeedsCleanup nc1 = new NeedsCleanup();
|
|
|
|
try {
|
|
|
|
// ...
|
|
|
|
} finally {
|
|
|
|
nc1.dispose();
|
|
|
|
}
|
|
|
|
|
2016-11-21 12:37:57 -08:00
|
|
|
// [2]:
|
2017-05-10 11:45:39 -06:00
|
|
|
// If construction cannot fail,
|
|
|
|
// you can group objects:
|
2015-06-15 17:47:35 -07:00
|
|
|
NeedsCleanup nc2 = new NeedsCleanup();
|
|
|
|
NeedsCleanup nc3 = new NeedsCleanup();
|
|
|
|
try {
|
|
|
|
// ...
|
|
|
|
} finally {
|
|
|
|
nc3.dispose(); // Reverse order of construction
|
|
|
|
nc2.dispose();
|
|
|
|
}
|
|
|
|
|
2016-11-21 12:37:57 -08:00
|
|
|
// [3]:
|
2015-06-15 17:47:35 -07:00
|
|
|
// If construction can fail you must guard each one:
|
|
|
|
try {
|
|
|
|
NeedsCleanup2 nc4 = new NeedsCleanup2();
|
|
|
|
try {
|
|
|
|
NeedsCleanup2 nc5 = new NeedsCleanup2();
|
|
|
|
try {
|
|
|
|
// ...
|
|
|
|
} finally {
|
|
|
|
nc5.dispose();
|
|
|
|
}
|
2016-01-25 18:05:55 -08:00
|
|
|
} catch(ConstructionException e) { // nc5 const.
|
2015-06-15 17:47:35 -07:00
|
|
|
System.out.println(e);
|
|
|
|
} finally {
|
|
|
|
nc4.dispose();
|
|
|
|
}
|
2016-01-25 18:05:55 -08:00
|
|
|
} catch(ConstructionException e) { // nc4 const.
|
2015-06-15 17:47:35 -07:00
|
|
|
System.out.println(e);
|
|
|
|
}
|
|
|
|
}
|
2015-09-07 11:44:36 -06:00
|
|
|
}
|
|
|
|
/* Output:
|
2015-06-15 17:47:35 -07:00
|
|
|
NeedsCleanup 1 disposed
|
|
|
|
NeedsCleanup 3 disposed
|
|
|
|
NeedsCleanup 2 disposed
|
|
|
|
NeedsCleanup 5 disposed
|
|
|
|
NeedsCleanup 4 disposed
|
2015-09-07 11:44:36 -06:00
|
|
|
*/
|