public class Finalize1 { private static final int testIter = 100; static public void main(String[] args) { int n; //Initialize a batch of objects that use Finalize to clean up for (n=testIter; --n>=0;) { UsesFinalize uf = new UsesFinalize(); } //Initialize a batch of objects that use an explicit close //to clean up. Note that the code is more complex. This //is a necessary evil. for (n=testIter; --n>=0;) { UsesClose uf = null; try { uf = new UsesClose(); } finally { if (uf != null) uf.close(); } } System.out.println("This demo demonstrates the danger of relying on finally to expediently close resources."); System.out.println("Testing with 100 resources:"); //Each of the classes tracking the maximum number of "open" resources //at any given time. System.out.println("Using Finalize to close resources required " + UsesFinalize.maxActive + " open resources."); System.out.println("Using explicit close required " + UsesClose.maxActive + " open resource."); } static public class UsesFinalize { static int active; static int maxActive; UsesFinalize() { active++; maxActive = Math.max(active, maxActive); } public void finalize() { active--; } } static public class UsesClose { static int active; static int maxActive; public UsesClose() { active++; maxActive = Math.max(active, maxActive); } public void close() { active--; } } }