About Java OutputStream thread security issues __java

Source: Internet
Author: User

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.



Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.