Using ThreadLocal Variables in Java
by Tom White


Listing One

import java.text.ParseException;
import java.util.Date;
public interface DateParser {
    public Date parse(String text) throws ParseException;
}


Listing Two

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

public class UnsynchronizedDateParser implements DateParser {
  private final DateFormat dateFormat = new SimpleDateFormat("dd/MM/yyyy");
  public Date parse(String text) throws ParseException {
    return dateFormat.parse(text);
  }
}


Listing Three

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

public class SynchronizedDateParser implements DateParser {
  private final DateFormat dateFormat = new SimpleDateFormat("dd/MM/yyyy");
  public synchronized Date parse(String text) throws ParseException {
    return dateFormat.parse(text);
  }
}


Listing Four

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

public class NewInstanceDateParser implements DateParser {
    public Date parse(String text) throws ParseException {
        return new SimpleDateFormat("dd/MM/yyyy").parse(text);
    }
}

Listing Five

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

public class ThreadLocalDateParser implements DateParser {
    private static final ThreadLocal DATE_PARSER_THREAD_LOCAL = 
                                                     new ThreadLocal() {
        protected Object initialValue() {
            return new SimpleDateFormat("dd/MM/yyyy");
        }
    };
    public Date parse(String text) throws ParseException {
        return ((DateFormat) DATE_PARSER_THREAD_LOCAL.get()).parse(text);
    }
}



2


