java中带初始化参数的并发安全单例



我想创建一个单例类Phone,这样它就可以初始化(带有number)并且也是并发安全的。所以,这是我带来的:

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;

public class PhoneTest {
    public static void main(String... args){
        System.out.println(Phone.getInstance().getNumber());
    }
    static final class Phone {
        private final String number;
        private final static Phone instance;
        static {
            instance = new Phone(PhonePropertyReader.readPhoneNumber());
        }
        private Phone(String number) {
            this.number = number;
        }
        public static Phone getInstance() {
            if (instance == null) throw 
                new IllegalStateException("instance was not initialized");
            return instance;
        }
        public String getNumber() {
            return number;
        }
    }

    static final class PhonePropertyReader {
        static String readPhoneNumber() {
            File file = new File("phone.properties");
            String phone = "";
            System.out.println(file.getAbsolutePath());
            if (!file.exists()) {
                return phone = "555-0-101";
            }
            try {
                BufferedReader r = new BufferedReader(new FileReader(file));
                phone = r.readLine().split("=")[1].trim();
                r.close();
            } catch (IOException e) {
            }
            return phone;
        }
    }
}
我也有一个文件电话。属性包含
phone=12345

这是一个好的解决方案吗?并发安全吗?

我相信Enum仍然是java中实现线程安全单例的最佳方式。

我不建议你使用单例(检查另一个问题)

否则,你的代码是线程安全的,因为你所做的唯一影响是在static {}区域,根据定义,线程安全。

顺便说一句,为什么不把你的readPhoneNumber()方法直接合并到你的phone类中呢?

最新更新