使用带有SDF的本地线程并在使用后将其删除

时间:2015-04-29 15:11:00

标签: java multithreading simpledateformat

使用简单日期格式不是线程安全的。为了避免它,使用ThreadLocal。它用于维护每个线程中的状态。 使用它时我们应该小心,因为它可能导致内存泄漏。 SDF在threadlocal上设置,稍后用于从中读取。 为防止内存泄漏,也应将其删除。 能否请您说明在SDF使用后需要删除本地线程的示例。

以下是代码

public class ConcurrentDateFormatAccess {

 private ThreadLocal<DateFormat> df = new ThreadLocal<DateFormat> () {

  @Override
  public DateFormat get() {
   return super.get();
  }

  @Override
  protected DateFormat initialValue() {
   return new SimpleDateFormat("yyyy MM dd");
  }

  @Override
  public void remove() {
   super.remove();
  }

  @Override
  public void set(DateFormat value) {
   super.set(value);
  }

 };

 public Date convertStringToDate(String dateString) throws ParseException {
  return df.get().parse(dateString);
 }
}

请帮助调用此函数的客户端代码以及处理threadLocal的删除部分

1 个答案:

答案 0 :(得分:0)

package com.so;

import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

public class ConcurrentDateFormatAccess {



    private static ThreadLocal<DateFormat> df = new ThreadLocal<DateFormat> () {

      @Override
      public DateFormat get() {
       return super.get();
      }

      @Override
      protected DateFormat initialValue() {
       return new SimpleDateFormat("yyyy MM dd");
      }

      @Override
      public void remove() {
       super.remove();
      }

      @Override
      public void set(DateFormat value) {
       super.set(value);
      }

     };

     public static  Date convertStringToDate(String dateString) throws ParseException {
      return df.get().parse(dateString);
     }

     public static void clean() throws ParseException {
           df.remove();
    }


    }

您的客户:

package com.so;

import java.text.ParseException;

public class SOQ {

    public static void main(String[] args) {

        Thread thread1 = new Thread() {
            @Override
            public void run() {
                try {
                    System.out.println(ConcurrentDateFormatAccess.convertStringToDate("2015 05 01"));
                    ConcurrentDateFormatAccess.clean();
                } catch (ParseException e) {// TODO Auto-generated catch block
                    e.printStackTrace();
                }

                super.run();
            }
        };
        Thread thread2 = new Thread() {
            @Override
            public void run() {
                try {
                    System.out.println(ConcurrentDateFormatAccess.convertStringToDate("2015 05 02"));
                    ConcurrentDateFormatAccess.clean();
                } catch (ParseException e) {
                    e.printStackTrace();
                }
                super.run();
            }
        };
        thread1.start();
        thread2.start();



    }

}