任何人都可以给我一个显示SimpleDateFormat的例子是线程不安全的



我试图编写一个示例以显示SimpleDateFormat是线程不安全的。但是它不起作用!谁能给我一个显示SimpleDateFormat的例子是线程不安全的吗?

public static void main(String[] args) throws ParseException, InterruptedException {
    Date aDate = (new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse("2016-12-15 23:59:59"));
    ExecutorService executor = Executors.newFixedThreadPool(Runtime.getRuntime().availableProcessors() * 1000);
    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    DataFormatter callable = new DataFormatter(sdf, aDate);
    Collection<DataFormatter> callables = Collections.nCopies(1000, callable);
    executor.invokeAll(callables);
    executor.shutdown();
}
private static class DataFormatter implements Callable<String> {
    private SimpleDateFormat sdf;
    private Date aDate;
    public DataFormatter(SimpleDateFormat sdf, Date aDate) {
        this.sdf = sdf;
        this.aDate = aDate;
    }
    @Override
    public String call() throws Exception {
        String format = sdf.format(aDate);
        Assert.assertEquals("2016-12-15 23:59:59", format);
        return format;
    }
}

任何人都可以给我一个示例,显示简单的formateFormat是线程不安全的吗?

当然。代码的问题在于,您正在一遍又一遍地尝试格式化相同的日期,因此共享字段永远不会保持不同的值。如果我们查看SimpleDateFormat的代码,我们会发现它扩展了具有共享Calendar calendar字段的DateFormat。这是班级的重新进入问题。

// shared with everyone else calling the same SimpleDateFormat
protected Calendar calendar;
...
// method from DateFormat that is extended by SimpleDateFormat
private StringBuffer format(Date date, StringBuffer toAppendTo, FieldDelegate delegate) {
    calendar.setTime(date);
    ...

顺便说一句,还要注意它使用StringBuffer,这意味着使用synchronized方法。令人沮丧的是,我们为同步性能罚款付费,但我们不会与SimpleDateFormat重新进入。

这是我对如何演示它的看法。我只是在随机日期两次运行日期格式并检查结果。它只有20个并发线程即可立即失败。

public class SimpleDateFormatEnosafe {
    private static final SimpleDateFormat format =
            new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    public static void main(String[] args) {
        ExecutorService executor = Executors.newCachedThreadPool();
        DataFormatter formatter = new DataFormatter();
        for (int i = 0; i < 20; i++) {
            executor.submit(formatter);
        }
        executor.shutdown();
        // NOTE: this could never finish if all but one thread fails in the pool
    }
    private static class DataFormatter implements Runnable {
        @Override
        public void run() {
            ThreadLocalRandom random = ThreadLocalRandom.current();
            while (true) {
                Date date = new Date(random.nextLong());
                String output1 = format.format(date);
                String output2 = format.format(date);
                if (!output1.equals(output2)) {
                    System.out.println(output1 + " != " + output2);
                    break;
                }
            }
        }
    }
}

我尝试过,事实证明这很容易。我有两个线程使用共享的SimpleDateFormat实例(声明为 DateFormat),将不同的日期格式化,但实际实例是SimpleDateFormat类)。这是我的代码:

public class FormattingThread extends Thread {
    private final static DateFormat shared = DateFormat.getDateTimeInstance(DateFormat.FULL, DateFormat.FULL, Locale.GERMANY);
    private final static ZoneOffset offset = ZoneOffset.ofHours(5);
    LocalDateTime date;
    public FormattingThread(LocalDateTime date) {
        super("FormattingThread");
        this.date = date;
    }
    @Override
    public void run() {
        final DateFormat myOwn = DateFormat.getDateTimeInstance(DateFormat.FULL, DateFormat.FULL, Locale.GERMANY);
        int stepCount = 0;
        while (true) {
            stepCount++;
            Date classical = Date.from(date.toInstant(offset));
            String formatted = myOwn.format(classical);
            String formattedThreadUnsafe = shared.format(classical);
            if (! formatted.equals(formattedThreadUnsafe)) {
                System.err.println("Mine " + formatted + "; shared " + formattedThreadUnsafe
                        + " in " + stepCount + " steps");
            }
            date = date.plusDays(23);
        }
    }
    public static void main(String[] args) {
        new FormattingThread(LocalDateTime.now()).start();
        new FormattingThread(LocalDateTime.now().plusHours(17)).start();
    }
}

在我的计算机上,其中一个线程从第一个调用format()获得了不正确的结果。从每个线程接到几百个电话后,ArrayIndexOutOfBoundsExceptionCalendar类中发生(SimpleDateFormat使用Calendar)。

我仍然想像已经说过的那样强调:类不是线程安全,不能保证您可以在多个线程中使用它时会出现错误。没有在彻底的测试中表现出来的同步错误的故事,然后在生产中浮出水面。我最近在Java程序中没有在Mac和Linux上发生的一个,但是Windows用户报告了它,我们必须快速发布错误修复版本。这样的事件非常昂贵。

相关内容

  • 没有找到相关文章

最新更新