File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
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

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?


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,


Andy Jung
Ranch Hand

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

thanks for the hint with the shutdown hook!

Roel De Nijs

Joined: Jul 19, 2004
Posts: 8393

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,

SCJA, SCJP (1.4 | 5.0 | 6.0), SCJD
I agree. Here's the link:
subject: call to close on RandomAccessFile
It's not a secret anymore!