aspose file tools*
The moose likes Developer Certification (SCJD/OCMJD) and the fly likes call to close on RandomAccessFile Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Certification » Developer Certification (SCJD/OCMJD)
Bookmark "call to close on RandomAccessFile" Watch "call to close on RandomAccessFile" New topic
Author

call to close on RandomAccessFile

Andy Jung
Ranch Hand

Joined: Feb 07, 2010
Posts: 150
Howdy ranchers!

When my server starts, there will be a reference to a permanently opened RandomAccessFile.
But where or when do I have to call the close operation on that file? Should I rely on the JVM to close this implicitly when the server shuts down, or should I explicitly place this operation in the finalize()-method of the singleton?

Regards,
Andy


SCJP, SCJD
Carlos Morillo
Ranch Hand

Joined: Jun 06, 2009
Posts: 221

Hi Andy,

Depending on the approach you take, either doing read()/write()s all the time and hangling IOExceptions
or using a cache in memory (I am following this approach and I find it a lot easier and it was also used by
Roberto Perillo and Roel De Nijs) you will need to use some mechanism that will no longer accept operations
on the database file.

In the Monkhouse book there is an example of this Shutdown hook locking the Database file.

This should take care of closing the file.

I would not use a finalize() method since they are run by the GC thread in the JVM and when it runs
it is not deterministic.

I'd do a search in this forum for shutdown hook, etc.


Hope this helps,


Carlos.


SCSA, OCA, SCJP 5.0, SCJD, CCDH, CCAH http://www.linkedin.com/in/carlosamorillo
Andy Jung
Ranch Hand

Joined: Feb 07, 2010
Posts: 150
Hi Carlos,

thanks for the hint with the shutdown hook!

Andy
Roel De Nijs
Bartender

Joined: Jul 19, 2004
Posts: 5408
    
  13

Hi Andy,

Carlos is correct: finalize is not guaranteed to run and should never be used to do clean up of your resources.

The addShutdownHook of the Runtime class will come to the rescue ;) If you use the search function you'll find plenty of threads discussing this issue

Kind regards,
Roel


SCJA, SCJP (1.4 | 5.0 | 6.0), SCJD
http://www.javaroe.be/
 
It is sorta covered in the JavaRanch Style Guide.
 
subject: call to close on RandomAccessFile