Monday, June 11, 2012

how to make a each object for each thread using the ThreadLocal


package com.yagapp.phaseone;

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

public class DateFormatTest {

// anonymous inner class. Each thread will have its own copy
private final static ThreadLocal<SimpleDateFormat> shortDateFormat = new ThreadLocal<SimpleDateFormat>() {
protected SimpleDateFormat initialValue() {
return new SimpleDateFormat("dd/MM/yyyy");
}
};

public Date convert(String strDate) throws ParseException {

// get the SimpleDateFormat instance for this thread and parse the date
// string
Date d = shortDateFormat.get().parse(strDate);
return d;
}

}

No comments:

Post a Comment