關於Java OutputStream 安全執行緒問題__Java

來源:互聯網
上載者:User

今天偶爾發現java的輸出資料流的安全執行緒問題

先看代碼吧

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 stubFile 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;}@Overridepublic 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 blocke.printStackTrace();}//}}}
這裡的輸出結果很有意思,會相互覆蓋,偶爾輸出

aaasdfasfd

有時候輸出

bb
dfasfd

輸出第二種是因為第一bb \r\n把第一個字串給覆蓋掉了

觀察Filetputtream的代碼,發現很有意思,整個類是非安全執行緒的,不過在類的注釋上沒有標記這一點,最底層的寫入是調用本地方法

 private native void writeBytes(byte b[], int off, int len, boolean append)

此處的相互覆蓋應該是底層沒有對並發進行處理,導致兩個線程同時在位元組流的同一位置進行寫入,應該還會有更奇怪的輸出

ab

dfasfd

不過這種輸出的重現幾率很小,理論上應該存在


再觀察DataOutputStream 發現只有write(byte b[])會加鎖,其他時候不會加鎖,不知到為何,難道是為了提升效能故意把鎖去掉了。



聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

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.