Win a copy of Learn Spring Security (video course) this week in the Spring forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

call to close on RandomAccessFile

 
Andy Jung
Ranch Hand
Posts: 150
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
 
Carlos Morillo
Ranch Hand
Posts: 221
Java Python Scala
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
Andy Jung
Ranch Hand
Posts: 150
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi Carlos,

thanks for the hint with the shutdown hook!

Andy
 
Roel De Nijs
Sheriff
Posts: 9780
101
AngularJS Chrome Eclipse IDE Hibernate Java jQuery MySQL Database Spring Tomcat Server
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic