Defensive copy of Calendar

前端 未结 7 1390
面向向阳花
面向向阳花 2021-01-04 00:38

Been trying to find the best way to implement a method that makes a defensive copy of a Calendar object.

eg:

public void setDate(Calendar date) {
            


        
7条回答
  •  别那么骄傲
    2021-01-04 01:05

    Just wrap your Calendar object into ThreadLocal. This will guarantee that each instance of Calendar is used only by one thread. Something like this:

    public class ThreadLocalCalendar
    {
        private final static ThreadLocal  CALENDAR =
            new ThreadLocal  ()
            {
                @Override
                protected Calendar initialValue()
                {
                    GregorianCalendar calendar = new GregorianCalendar();
    
                    // Configure calendar here.  Set time zone etc.
    
                    return calendar;
                }
            };
    
        // Called from multiple threads in parallel
        public void foo ()
        {
            Calendar calendar = CALENDAR.get ();
    
            calendar.setTime (new Date ());
            // Use calendar here safely, because it belongs to current thread
        }
    }
    

提交回复
热议问题