Skip to content

Commit d8cd45b

Browse files
committed
Allocations optimization
See pull request Allocations optimization for converters quickfix-j#34
1 parent c0901c3 commit d8cd45b

File tree

1 file changed

+33
-10
lines changed

1 file changed

+33
-10
lines changed

quickfixj-core/src/main/java/quickfix/field/converter/UtcDateOnlyConverter.java

+33-10
Original file line numberDiff line numberDiff line change
@@ -29,10 +29,20 @@
2929
* Convert between a date and a String
3030
*/
3131
public class UtcDateOnlyConverter extends AbstractDateTimeConverter {
32+
33+
protected static final class Context {
34+
private final DateFormat dateFormat = createDateFormat("yyyyMMdd");
35+
private final StringBuffer buffer = new StringBuffer(128);
36+
}
37+
3238
// SimpleDateFormats are not thread safe. A thread local is being
3339
// used to maintain high concurrency among multiple session threads
34-
private static final ThreadLocal<UtcDateOnlyConverter> utcDateConverter = new ThreadLocal<UtcDateOnlyConverter>();
35-
private final DateFormat dateFormat = createDateFormat("yyyyMMdd");
40+
private static final ThreadLocal<Context> utcDateConverter = new ThreadLocal<Context>() {
41+
@Override
42+
protected Context initialValue() {
43+
return new Context();
44+
}
45+
};
3646

3747
/**
3848
* Convert a date to a String ("YYYYMMDD")
@@ -41,16 +51,29 @@ public class UtcDateOnlyConverter extends AbstractDateTimeConverter {
4151
* @return the formatted date
4252
*/
4353
public static String convert(Date d) {
44-
return getFormatter().format(d);
54+
Context context = utcDateConverter.get();
55+
try {
56+
context.dateFormat.format(d, context.buffer, DontCareFieldPosition.INSTANCE);
57+
return context.buffer.toString();
58+
} finally {
59+
context.buffer.setLength(0);
60+
}
4561
}
4662

47-
private static DateFormat getFormatter() {
48-
UtcDateOnlyConverter converter = utcDateConverter.get();
49-
if (converter == null) {
50-
converter = new UtcDateOnlyConverter();
51-
utcDateConverter.set(converter);
63+
/**
64+
* Convert a date to a String ("YYYYMMDD")
65+
*
66+
* @param d the date to convert
67+
* @param stringBuilder the out buffer to hold formatted date
68+
*/
69+
public static void convert(Date d, StringBuilder stringBuilder) {
70+
Context context = utcDateConverter.get();
71+
try {
72+
context.dateFormat.format(d, context.buffer, DontCareFieldPosition.INSTANCE);
73+
stringBuilder.append(context.buffer);
74+
} finally {
75+
context.buffer.setLength(0);
5276
}
53-
return converter.dateFormat;
5477
}
5578

5679
/**
@@ -66,7 +89,7 @@ public static Date convert(String value) throws FieldConvertError {
6689
assertLength(value, 8, type);
6790
assertDigitSequence(value, 0, 8, type);
6891
try {
69-
d = getFormatter().parse(value);
92+
d = utcDateConverter.get().dateFormat.parse(value);
7093
} catch (ParseException e) {
7194
throwFieldConvertError(value, type);
7295
}

0 commit comments

Comments
 (0)