`
cloudtech
  • 浏览: 4613469 次
  • 性别: Icon_minigender_1
  • 来自: 武汉
文章分类
社区版块
存档分类
最新评论

Java时区bug,TimeZone.setDefault()只在当前线程和之后创建的子线程有效

 
阅读更多

项目是基于GMT时间的,在系统启动的时候,我们就会调用TimeZone.setDefault(timeZone)将默认时区设为GMT。
后来突然发现,有时用户选择的时间经过后台一圈后回产生8个小时误差。又是间歇性的,要他重现的时候又偏不来。苦心debug,终于发现在部分线程中,时区还是GMT+8,后台某个调用可能把时区变为了GMT,8小时误差就产生了。网上一搜,原来是bug:

http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=6352812
只在部分电脑上有问题,幸好production上是好的,写了一个程序来测试:

import java.util.Date;
import java.util.TimeZone;

public class Test {
@SuppressWarnings("unused")
public static void main(String[] args) throws InterruptedException {
DateThread thread = new DateThread();
thread.start();
TimeZone gmt = TimeZone.getTimeZone("GMT");

Date now = new Date();
System.out.println("main thread,before set timezone:" + now.toString());
TimeZone.setDefault(gmt);
Thread.currentThread().sleep(2000);
thread.resume();
System.out.println("main thread,after set timezone:" + now.toString());

}

}

class DateThread extends Thread {
@SuppressWarnings( { "unused", "deprecation" })
public void run() {
Date now = new Date();
System.out.println("sub thread,before set timezone:" + now.toString());
this.suspend();
System.out.println("sub thread,after set timezone:" + now.toString());
}
}
如果子线程输出的时区一样,就说明有bug

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics