今天偶尔发现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 stub
- 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+" ").getBytes());
- // TimeUnit.SECONDS.sleep(new Random().nextInt(10));
- } catch (Exception e) {
- // TODO Auto-generated catch block
- e.printStackTrace();
- }
- // }
- }
- }
这里的输出结果很有意思,会相互覆盖,偶尔输出
aaasdfasfd
有时候输出
bb
dfasfd
输出第二种是因为第一bb 把第一个字符串给覆盖掉了
观察Filetputtream的代码,发现很有意思,整个类是非线程安全的,不过在类的注释上没有标记这一点,最底层的写入是调用本地方法
- private native void writeBytes(byte b[], int off, int len, boolean append)
此处的相互覆盖应该是底层没有对并发进行处理,导致两重生之大文豪个线程同时在字节流的同一位置进行写入,应该还会有更奇怪的输出
ab
dfasfd
不过这种输出的重现几率很小,理论上应该存在
再观察DataOutputStream 发现只有write(byte b[])会加锁,其他时候不会加锁,不知到为何,难道是为了提升性能故意把锁去掉了?