未能进行双重锁定检查的java代码

时间:2016-01-15 07:42:01

标签: java concurrency singleton double-checked-locking

注意:我知道在java 5之前(2004年给出),在java中,双重检查锁定会失败,即使你将“volatile”添加到“instance”字段。在java 5之后,volatile的语义已经适合双重检查锁。由于无序执行,我甚至在java5之后也知道without "volatile", double checking lock will fail。但是,我的问题是:如何编写代码来证明(双重检查锁定会在没有“volatile”的情况下失败)???

我已经阅读了很多文章说在Java中双重检查锁会失败,所以我认为下面的代码试图获得SocketFactory的单例实例,会失败(因为“实例”字段不是易变的):< / p>

  private static SocketFactory instance  = null;
  private static SocketFactory getInstance() {
      if (instance == null) {
         synchronized (SocketFactory.class){
            if (instance == null){
               instance = new SocketFactory(); // line 1
            }
         }
      }
      return instance;
   }

但问题是,如果上面的代码失败了,我怎么能证明这一点?我试着写下面的代码(我想,如果第1行将被重新排序,“实例”引用可能指向一个SocketFactory对象,其中“construct”字段为“false”):

import java.io.*;
import java.nio.*;
import java.nio.file.*;

public class TIJ_doubleCheckingLock {

    static TIJ_doubleCheckingLock instance;

    private Object lock;

    private boolean constructed = false;

    {   
        constructed = false;
    }

    private TIJ_doubleCheckingLock() {
        try{
            Thread.sleep(10000);
        } catch(Exception e) {
        }
        constructed = true;
    }

    static TIJ_doubleCheckingLock getInstance() {
        if (instance == null) {
            synchronized (TIJ_doubleCheckingLock.class) {
                try{
                    Thread.sleep(1000);
                } catch(Exception e) {

                }
                if(instance == null) {
                    instance = new TIJ_doubleCheckingLock();
                }
            }
        }
        return instance;
    }

    public static void main(String args[]) {
        class MyThread extends Thread {
                @Override
                public void run() {

                    TIJ_doubleCheckingLock instance = TIJ_doubleCheckingLock.getInstance();
                    String fileName = "TIJ_doubleCheckingLockResult.txt";
                    java.io.File file = new File(fileName);
                    try {
                        if(!instance.constructed) {
                            java.nio.file.Files.write(Paths.get(file.toURI()), (instance.constructed+"").
                                    getBytes("utf-8"), StandardOpenOption.CREATE, StandardOpenOption.APPEND);
                        }
                    } catch (Exception e) {
                    }
                }

        }

        Thread firstThread = new MyThread();
        firstThread.start();

        try{
            Thread.sleep(5000);
        } catch(Exception e) {}


        for(int i=0;i<10;i++) {
            Thread thread = new MyThread(); 
            thread.start();
        }
    }
}

但我从未在txt文件中看到“false”。 那么如何证明双重检查锁定会失败呢?

2 个答案:

答案 0 :(得分:1)

双重检查锁定was broken in Java。您的代码适用于Java 5及更高版本。 JVM收到了new memory model

此外,您的代码需要volatile关键字。

private static volatile SocketFactory instance;

答案 1 :(得分:-1)

你需要知道我的代码在synchronized中的区别:

import java.util.concurrent.BrokenBarrierException;
import java.util.concurrent.CyclicBarrier;

/**
 * @author heyunxia (love3400wind@163.com)
 * @version 1.0
 * @since 2016-01-15 下午3:50
 */
public class SocketFactoryTest {

    public static void main(String[] args) {
        SocketFactoryTest test = new SocketFactoryTest();
        test.run();

    }

    private static final int COUNTER = 20;

    CyclicBarrier barrier = new CyclicBarrier(COUNTER);

    public void run(){
        for(int i=0; i<COUNTER; i++) {
            new Thread(new Runnable() {
                @Override
                public void run() {
                    SocketFactory.getInstance(barrier);
                }
            }).start();
        }
    }

}


class SocketFactory {
    private static SocketFactory instance = null;

    public static SocketFactory getInstance(CyclicBarrier barrier) {
        if (instance == null) {
            try {
                barrier.await();
            } catch (InterruptedException e) {
                e.printStackTrace();
            } catch (BrokenBarrierException e) {
                e.printStackTrace();
            }
            synchronized (SocketFactory.class) {
                // option 1
                instance = new SocketFactory();
                System.out.println(Thread.currentThread().getName() + "***");

                /*
                // option 2
                if (instance == null) {
                    System.out.println(Thread.currentThread().getName() + "***");
                    instance = new SocketFactory();
                }else {
                    System.out.println(Thread.currentThread().getName() + "-have already instanced...");
                }*/
            }
        }
        return instance;
    }
}