> This changes the way a programmer writes code. A C++ class > and function that uses the class looks like this: > > class A > { > public: > A(){...grab some resources...} > ~A(){...release the resources...} > } > > void f() > { > A a; > ... use a's resources ... > } > > ...looks like this in Java... > > class A > { > public: > A(){...grab some resources...} > } > > void f() > { > try > { > A a; > ... use a's resources ... > } > finally > { > ...release the resources... > } > }
This is exactly the right way to do things in Java. In Java, you can open hundreds of files, and never trigger any gc, since each file object is very small. Unless you explicit close file, you will be dead very quickly. The difference between C++ and Java is C++ provides you stack allocated object, and compiler does the dirty job to make sure the dtors are called at the right time. In Java, you have to do it yourself. In case you make some mistakes, the finalizer will kick in. But you should not rely on it. From the runtime poit of view, the above C++ and Java are almost the same, except the memory deallocation. This is one of the reason Java is so sloppy. Everyone relies on language feature to do their job, but it is impossible for JVM to know there are several file objects in thousands of dead object, which need to be finalized in order to free enough file descriptor. All you need to do is to treat Java object as C++ heap object, period. Hong