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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值