Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/333.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/multithreading/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 在多线程环境中使用DateFormat时使用synchronized关键字_Java_Multithreading_Simpledateformat_Indexoutofboundsexception - Fatal编程技术网

Java 在多线程环境中使用DateFormat时使用synchronized关键字

Java 在多线程环境中使用DateFormat时使用synchronized关键字,java,multithreading,simpledateformat,indexoutofboundsexception,Java,Multithreading,Simpledateformat,Indexoutofboundsexception,在多线程环境中使用DateFormat时,在何处使用synchronized关键字 我在异常下面: java.lang.ArrayIndexOutOfBoundsException: -1 当我查看我的代码时,我有一个方法可以使用SimpleDateFormat格式化日期 public static synchronized String now(String dateFormat) { if (dateFormat.equalsIgnoreCase("")) {

在多线程环境中使用DateFormat时,在何处使用synchronized关键字

我在
异常
下面:

java.lang.ArrayIndexOutOfBoundsException: -1
当我查看我的代码时,我有一个方法可以使用
SimpleDateFormat
格式化日期

public static synchronized String now(String dateFormat) {

            if (dateFormat.equalsIgnoreCase("")) {
                dateFormat = "yyyy-MM-dd'T'HH:mm:ss";
            }
            Calendar cal = Calendar.getInstance();
            SimpleDateFormat sdf = null;
            if (dateFormat == null || dateFormat.equalsIgnoreCase("")) {
                sdf = new SimpleDateFormat();
            } else {
                sdf = new SimpleDateFormat(dateFormat, Locale.getDefault());
            }
            return sdf.format(cal.getTime());

        }
虽然我无法重现异常,但这可能是我遇到
java.lang.ArrayIndexOutOfBoundsException
的地方,因为我发现了一个描述如何在多线程环境中使用
DateFormat
DateFormat
不同步,因此在多线程环境中工作时可能会引发
java.lang.ArrayIndexOutOfBoundsException

但是我上面的方法已经是
synchronized
方法了

我的问题是:

静态方法是否可以是
同步的
方法


我是否需要同步
SimpleDataFormat
的对象而不是
synchronized
方法?为什么?

上面显示的方法不访问任何共享状态(DateFormat创建为局部变量),因此您根本不需要同步它


您需要找到与异常关联的stacktrace。否则这只是猜测工作。

您可以看一看,在您的示例中,
SimpleDataFormat
是一个局部变量,因此它是线程安全的,因为它是“线程局部的”。顺便说一下,该方法根本不需要同步。