TimeZone.setDefault changes in JDK6

纵饮孤独 提交于 2019-11-27 04:33:21

问题


I just noticed that JDK 6 has a different approach to setting a default TimeZone than JDK5.

Previously the new default would be stored in a thread-local variable. With JDK6 (I just reviewed 1.6.0.18) the implementation has changed, so that if the user can write to the "user.timezone" property, or if there is no SecurityManager installed, the timezone changes VM-wide! Otherwise a thread-local change occurs.

Am I wrong? This seems to be quite a drastic change, and I couldn't find anything on the web about it.

Here is the JDK6 code:

 private static boolean hasPermission() {
  boolean hasPermission = true;
  SecurityManager sm = System.getSecurityManager();
  if (sm != null) {
   try {
    sm.checkPermission(new PropertyPermission("user.timezone", "write"));
   } catch (SecurityException e) {
    hasPermission = false;
   }
  }
  return hasPermission;
 }

 /**
  * Sets the <code>TimeZone</code> that is
  * returned by the <code>getDefault</code> method.  If <code>zone</code>
  * is null, reset the default to the value it had originally when the
  * VM first started.
  * @param zone the new default time zone
  * @see #getDefault
  */
 public static void setDefault(TimeZone zone)
 {
  if (hasPermission()) {
   synchronized (TimeZone.class) {
    defaultTimeZone = zone;
    defaultZoneTL.set(null);
   }
  } else {
   defaultZoneTL.set(zone);
  }
 }

while before (in JDK5) it was simply:

 /**
  * Sets the <code>TimeZone</code> that is
  * returned by the <code>getDefault</code> method.  If <code>zone</code>
  * is null, reset the default to the value it had originally when the
  * VM first started.
  * @param zone the new default time zone
  * @see #getDefault
  */
 public static synchronized void setDefault(TimeZone zone)
 {
  defaultZoneTL.set(zone);
 }

回答1:


Searching the bugs database was actually quite a good idea :)

http://bugs.sun.com/view_bug.do?bug_id=6352812

and also (re docs):

http://bugs.sun.com/view_bug.do?bug_id=6181786

Summary: JDK 1.5 was an exception to the rule, with JDK 1.6 things are back to 'normal', which, according to the docs, is that a timezone change is VM wide.




回答2:


This was probably done to fix a bug. I'd search bugs.sun.com to find the rationale for it. (Clues might also be found in the release notes.)




回答3:


The API documentation for TimeZone.getDefault() states that "the source of the default TimeZone may vary with implementation." If your code relies on implementation specific behaviour of the standard API classes (in this case, that the default time zone is kept at a thread local level), you must expect that your code fails with newer versions of the VM or with VMs from different vendors.



来源:https://stackoverflow.com/questions/2176784/timezone-setdefault-changes-in-jdk6

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!