java - Why do I need to call a close() or shutdown() method? -
i'm new in java background in c++ in high school years. i'm trying make , chose java programming language.
i've done homework , lot "destructors" java, finalize() method, , close() or shutdown() methods. still think don't have idea of how should work (more info below of course)
ok, concrete question why need call close() or shutdown() methods?
in particular case i'm working class didn't develop handles smart card reader, i've seen case of file management, have call close() method, similar.
isn't calling close() method same idea freeing memory in c++ (that sucks)? meaning, have take care of deletion or destruction of object... isn't gc for?
it option class i'm trying use smart card reader not best, might better class implements finalize() method when no longer used , ready gc, frees memory (most native code) and/or frees hardware resources gc might not know how do.
but file management classes? used , maintained, why still needed close() method? understand purpose of existence, unlock file, why have remember close it? once object not used more unlock file automatically, @ least in common cases.
finally, proper workaround wrap class needs closed or shutdown class implements finalize() method , there call close() or shutdown() method?
i've seen finalize() method not popular, why i'm asking how problem should solved.
thanks in advance
juan
ps: i've seen:
why ever implement finalize()?
http://www.codeguru.com/java/tij/tij0051.shtml
most classes clean external resources in finalize
methods, isn't analogous c++'s destructor - destructor called object no longer used, finalizer isn't called until object garbage-collected, , don't know when going happen (and might never happen if don't have memory-intensive program). let's you're allocating bunch of objects each allocating database connection (yes, should using connection pooling, hypothetical); use each object , null out references can garbage-collected without first closing database connections, , database going crap out on because it's got many connections open. can call system.gc
in hopes clean connections, suggestion garbage-collector perform collection, , it's possible garbage database connections' finalizers aren't smart enough clean connections.
long story short, need call close
, shutdown
because don't know if/when objects' finalizers going run, , don't know how @ cleaning external resources.
incidentally, should use try-catch-finally blocks make sure call close
, shutdown
- put methods in block. or if you're using java7, use try-with-resources.
Comments
Post a Comment