0

What happens, when calling filechannel.force and throws an exception?

When filechannel.write was successful and we were able to write the whole buffer content into the filechannel i want to be sure if everything was flushed to disk. I'll call force(true), which can throw an exception. What happens with data i wrote into filechannel? Was nothing flushed to disk or may be some part of data is flushed? How can i rollback the operation?

public boolean flush(ByteBuffer[] buffers, long buffersRemaining)
{
    try
    {
        FileChannel fileChannel = new RandomAccessFile(target, "rw").getChannel();
         long writtenBytes = fileChannel.write(buffers);  
         //we think we have written all the data into filechannel
         if(writtenBytes == buffersRemaining)
         {
            //we try to flush, but we get an exception
            try
            {
                fileChannel.force(true);
                fileChannel.close();
            }
            catch(IOException exception)
            {
                //???
                return false;
            }
         }                 
    }
    catch(Exception exception)
    {
      //log exception
      return false;
    }
}
  • Who knows. Maybe the drive is failing, there's no rollback in a regular filesystem, so you can't do much. – Kayaman Jul 29 '14 at 09:32
  • If you need rollback you should be using a a database. Otherwise you are essentially trying to design and implement one. – user207421 Jul 29 '14 at 09:48

1 Answers1

0

You should only try to handle exceptions if you can do something about them. This is one of these cases where it does not make sense. This should not happen normally, just log the exception and fail gracefully.

Uku Loskit
  • 40,868
  • 9
  • 92
  • 93