Today's occasional Java output stream thread safety problem
Look at the code first.
Import Java.io.File;
Import Java.io.FileInputStream;
Import Java.io.FileOutputStream;
Import Java.io.OutputStream;
Import Java.util.Random;
Import Java.util.concurrent.TimeUnit; public class Testfilewrite {public static void main (string[] args) throws Exception {//TODO auto-generated Method St
UB file F = new file ("a" +system.currenttimemillis ());
F.createnewfile ();
Java.util.concurrent.CountDownLatch CWL = new Java.util.concurrent.CountDownLatch (2);
FileOutputStream fos = new FileOutputStream (f);
New Thread (New Writethread (Cwl,fos, "BB"). Start ();
New Thread (New Writethread (Cwl,fos, "AAASDFASFD")). Start ();
Cwl.countdown ();
Cwl.countdown ();
TimeUnit.SECONDS.sleep (1);
Fos.flush ();
FileInputStream f1 = new FileInputStream (f);
byte[] ByteArray = new byte[1024];
int n = f1.read (ByteArray);
F1.close ();
System.out.println (New String (bytearray,0,n));
} class Writethread implements runnable{outputstream OS = null;
String Fspe = null; Java.util.concurRent.
Countdownlatch CWL;
Public Writethread (Java.util.concurrent.CountDownLatch cwl,outputstream os, String Fspe) {super ();
THIS.CWL = CWL;
This.os = OS;
This.fspe = Fspe;
@Override public void Run () {//for (int i=0;i<10;i++)//{try {cwl.await ();
Os.write ((fspe+ "\ r \ n"). GetBytes ());
TimeUnit.SECONDS.sleep (New Random (). Nextint (10));
catch (Exception e) {//TODO auto-generated catch block E.printstacktrace ();
}
// }
}
}The output here is interesting, it will cover each other, and occasionally output
Aaasdfasfd
Sometimes the output
Bb
Dfasfd
Output the second is because the first BB \ r \ n has overwritten the first string.
Looking at Filetputtream's code, it is interesting to note that the entire class is not thread-safe, but it is not marked on the annotation of the class, and the lowest write is to invoke the local method
Private native void Writebytes (byte b[], int off, int len, Boolean append)
The mutual overlay here should be that the underlying does not process concurrency, causing two threads to write simultaneously at the same location in the byte stream, and there should be more bizarre output
Ab
Dfasfd
But this kind of output is very unlikely to reproduce, and theoretically should exist.
Then observe DataOutputStream found only write (byte b[]) will add locks, other times will not lock, do not know why, is to enhance the performance of the lock removed deliberately.