[concurrency-interest] Doubt on happens-before and I/O operations.

Mark Thornton mthornton at optrak.co.uk
Fri Aug 15 11:13:55 EDT 2008


Fabio Cechinel Veronez wrote:
> Hello all,
>
> I have a doubt (maybe a dummy one) about happens-before relation and
> I/O operations.
>
> In the following example code.
>
> 01: class FileItem {
> 02:     private final File target;
> 03:     private volatile boolean written = false;
> 04:
> 05:     public FileItem(File target) {
> 06:         this.target = target;
> 07:     }
> 08:
> 09:     public void initialize() throws IOException {
> 11:         if (written)
> 12:             return;
> 13:         OutputStream out = new FileOutputStream(target);
> 14:         try {
> 15:             byte[] content = // retrieves the content from somewhere ...
> 16:             out.write(content);
> 17:         } finally {
> 18:             out.close();
> 19:         }
> 20:         written = true;
> 21:     }
> 22:
> 23:     public InputStream stream() throws IOException {
> 24:         if (!written)
> 25:             throw new IllegalStateException("unwritten data");
> 26:         return new FileInputStream(target);
> 27:     }
> 28: }
>
> Is it safe to say that once a Thread X reachs line 26 the content was
> completely written into the 'target' file or is it possible to have
> any reordering concerning the write on 'written' field (line 20) and
> the output operation?
>
> Thanks in advance.
>   
It s possible for two threads (or more) to be simultaneously executing 
lines 13 - 20. The first one to reach line 20 will set written to true, 
but the second thread will still be writing data. So the file may be 
incomplete or may contain multiple copies of the data. I would not 
recommend using volatile in this way.

Mark Thornton




More information about the Concurrency-interest mailing list