Uploaded image for project: 'JDK'
  1. JDK
  2. JDK-8210142

java.util.Calendar.clone() doesn't respect sharedZone flag

XMLWordPrintable

    • b11
    • x86_64
    • windows_10

      A DESCRIPTION OF THE PROBLEM :
      While analizing a heapdump of Jenkins, i noticed a 1:1 relation between Calendar and TimeZone instances.
      Further research showed the source of the issue, all Calender instances are cloned before they are stored in private fields. The java.util.Calendar.clone() doesn't respect sharedZone flag and creates a clone of TimeZone even if sharedZone is true.
      This results in Calendar instances with sharedZone = true and a fresh copy of the TimeZone.



      STEPS TO FOLLOW TO REPRODUCE THE PROBLEM :
      Run the provided source code


      ---------- BEGIN SOURCE ----------

          public static void main(String[] args) throws NoSuchFieldException, IllegalAccessException {
              // we need reflection to show this, sorry ...
              Field zone = Calendar.class.getDeclaredField("zone");
              zone.setAccessible(true);
              Field sharedZone = Calendar.class.getDeclaredField("sharedZone");
              sharedZone.setAccessible(true);

              // create a new calendar with any date
              Calendar c = new GregorianCalendar();

              // c should have a shared zone
              if (sharedZone.getBoolean(c)) {
                  // get a clone of the date
                  Calendar c2 = (Calendar) c.clone();
                  
                  // c2 has a shared zone too
                  if (sharedZone.getBoolean(c2)) {
                      
                      // the original calendar and the clone should have the same zone now
                      if (zone.get(c) != zone.get(c2)) {
                          throw new IllegalStateException("Both calendars have a shared zone, it should be the identical one");
                      }
                  }
              }
          }

      ---------- END SOURCE ----------

      FREQUENCY : always


            naoto Naoto Sato
            webbuggrp Webbug Group
            Votes:
            0 Vote for this issue
            Watchers:
            2 Start watching this issue

              Created:
              Updated:
              Resolved: