Search code examples
javaniofilechannel

What happens with written data if Filechannel.force(true) throws an exception?


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;
    }
}

Solution

  • 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.