java in SimpleDateFormater thread-safety issues and solutions

Recently saw an article in the SimpleDateFormater this class. He said the class is no problem in single-threaded programs, but in a multithreaded environment will thread safety issues.

Out of interest on this issue of verification. There are many online articles about this issue, but also resolve the reason. The main reason is because the conversion date SimpleDateFormat is operated by the Calendar object, SimpleDateFormat DateFormat class inheritance, DateFormat class maintains a Calendar object when multiple threads simultaneously manipulate the objects will be a problem.

So help it solve? . There are several

1. Try not to share in the use of SimpleDateFormater time, every time when they are creating a new object

2. Use ThreadLocal objects to wrap it formater

        ThreadLocal<SimpleDateFormat> local = new ThreadLocal<>();
        SimpleDateFormat sdf =  local.get();

3. Use LocalDateTime this class to date conversion and processing (recommended)

For the third method, focus on what this class.

This class is a utility class java8 eh launch date of a process, in Time package.

There are three main categories LocalDate, LocalTime, LocalDateTime. The first one is for the date, hour, minute, second for the third year, month, day, hour is a plus

Here to LocalDateTime for example, are some methods

        //获取当前时间
        LocalDateTime ldt = LocalDateTime.now();
        //给定年月日时分秒获取时间
        LocalDateTime ldt2 = LocalDateTime.of(2019, 1, 1, 1, 1, 1);
        //给定年月日时分秒毫秒获取时间
        LocalDateTime ldt3 = LocalDateTime.of(2019, 1, 1, 1, 1, 1, 1);
        //给时间字符串获取时间
        LocalDateTime ldt4 = LocalDateTime.parse("2019-01-10T17:07:05");
        //获取LocalDateTime对象当月的第一天
        LocalDateTime firstDayOfThisMonth = ldt4.with(TemporalAdjusters.firstDayOfMonth());
        //获取LocalDateTime对象当月的第二天
        LocalDateTime secondDayOfThisMonth = ldt4.withDayOfMonth(2);
        //获取LocalDateTime对象当月的最后一天
        LocalDateTime lastDayOfThisMonth = ldt4.with(TemporalAdjusters.lastDayOfMonth());
        //获取LocalDateTime对象的后一天
        LocalDateTime newtDay = ldt4.plusDays(1);
        //获取LocalDateTime对象的当月第一个周一
        LocalDateTime firstMondayOfDay = ldt4.with(TemporalAdjusters.firstInMonth(DayOfWeek.MONDAY));

        //获取LocalDateTime对象的年,月,日
        int year = ldt4.getYear();
        int month = ldt4.getMonthValue();
        int day = ldt4.getDayOfMonth();


        //前一天
        LocalDate l2 = ld.minusDays(1);
        //后一天
        LocalDate l3 = ld.plusDays(1);

These are some of the methods frequently used, there are many methods not listed, interested can go to find an official api.

Guess you like

Origin blog.csdn.net/github_39538842/article/details/89354360