【问题标题】:ThreadLocal variable for SimpleDateFormat (OR) new SimpleDateFormat - Correct?SimpleDateFormat (OR) new SimpleDateFormat 的 ThreadLocal 变量 - 正确吗?
【发布时间】:2014-03-10 11:14:56
【问题描述】:

我遇到this article 并感到困惑

在我们的项目中,有几个地方我们使用 ThreadLocal 来构造 ThreadLocal 变量

在其他几个地方,我们正在私有本地方法中构造一个新对象 SimpleDateFormat。

例子,

private Date getConvertedDate(String Date){
  SimpleDateFormat sdf = new SimpleDateFormat(); --> It is thread safe or not
}

谁能详细解释一下?

谢谢。

【问题讨论】:

    标签: java thread-safety


    【解决方案1】:

    在方法内部创建的变量 - 存在于堆栈中,因此它们不会跨线程共享。每个线程都有自己的堆栈。在方法中声明它,然后使用它,然后简单地忘记它,将使它成为线程安全的。

    在 cmets 之后这里是一个 sn-p:

    public class DeleteMe {
    
        public static void main(String[] args) throws Exception {
            DeleteMe me = new DeleteMe();
            me.go();
        }
    
        public void go() throws Exception {
            final Mutable mutable = new Mutable();
            new Thread(new Runnable() {
                @Override
                public void run() {
                    mutable.setT(57);
                }
            }).start();
            /** Main thread waits a bit to be sure that the custom Thread will start */
            Thread.sleep(2000);
            System.out.println(mutable.getT());
        }
    
        private class Mutable{
            public int t = 0;
    
            public int getT() {
                return t;
            }
    
            public void setT(int t) {
                this.t = t;
            }
        }
    }
    

    【讨论】:

    • 添加了一个小注释,如果内部类(如果变量声明为 final)也可以访问该变量,如果它在范围内,所以从技术上讲这可能不是线程安全的,但这很容易检查。
    • Gabor 能否请您提供示例代码 sn-p?
    • @GáborBakos Method Local 内部类只能被访问该方法本身的线程访问,即使实例位于堆上,也没有人可以引用它,因此对其进行更改。
    • @Eugene 我不确定你是对的:final SimpleDataFormat sdf = ...; new Thread() {public void run() {sdf.format(...);} }.start();
    • @GáborBakos 这实际上是个好点:)谢谢你的评论。
    猜你喜欢
    • 1970-01-01
    • 2018-10-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-11-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多