org.macrocloud.kernel.toolkit.utils.ConcurrentDateFormat Maven / Gradle / Ivy
package org.macrocloud.kernel.toolkit.utils;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;
import java.util.Queue;
import java.util.TimeZone;
import java.util.concurrent.ConcurrentLinkedQueue;
/**
* 参考tomcat8中的并发DateFormat
*
* {@link SimpleDateFormat}的线程安全包装器。
* 不使用ThreadLocal,创建足够的SimpleDateFormat对象来满足并发性要求。
*
.
*
* @author macro
*/
public class ConcurrentDateFormat {
/** The format. */
private final String format;
/** The locale. */
private final Locale locale;
/** The timezone. */
private final TimeZone timezone;
/** The queue. */
private final Queue queue = new ConcurrentLinkedQueue<>();
/**
* Instantiates a new concurrent date format.
*
* @param format the format
* @param locale the locale
* @param timezone the timezone
*/
private ConcurrentDateFormat(String format, Locale locale, TimeZone timezone) {
this.format = format;
this.locale = locale;
this.timezone = timezone;
SimpleDateFormat initial = createInstance();
queue.add(initial);
}
/**
* Of.
*
* @param format the format
* @return the concurrent date format
*/
public static ConcurrentDateFormat of(String format) {
return new ConcurrentDateFormat(format, Locale.getDefault(), TimeZone.getDefault());
}
/**
* Of.
*
* @param format the format
* @param timezone the timezone
* @return the concurrent date format
*/
public static ConcurrentDateFormat of(String format, TimeZone timezone) {
return new ConcurrentDateFormat(format, Locale.getDefault(), timezone);
}
/**
* Of.
*
* @param format the format
* @param locale the locale
* @param timezone the timezone
* @return the concurrent date format
*/
public static ConcurrentDateFormat of(String format, Locale locale, TimeZone timezone) {
return new ConcurrentDateFormat(format, locale, timezone);
}
/**
* Format.
*
* @param date the date
* @return the string
*/
public String format(Date date) {
SimpleDateFormat sdf = queue.poll();
if (sdf == null) {
sdf = createInstance();
}
String result = sdf.format(date);
queue.add(sdf);
return result;
}
/**
* Parses the.
*
* @param source the source
* @return the date
* @throws ParseException the parse exception
*/
public Date parse(String source) throws ParseException {
SimpleDateFormat sdf = queue.poll();
if (sdf == null) {
sdf = createInstance();
}
Date result = sdf.parse(source);
queue.add(sdf);
return result;
}
/**
* Creates the instance.
*
* @return the simple date format
*/
private SimpleDateFormat createInstance() {
SimpleDateFormat sdf = new SimpleDateFormat(format, locale);
sdf.setTimeZone(timezone);
return sdf;
}
}
© 2015 - 2024 Weber Informatics LLC | Privacy Policy