Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

#24 Cache NumberFormat instances on a thread level. #25

Open
wants to merge 1 commit into
base: 3.x
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@

import java.text.DecimalFormat;
import java.text.NumberFormat;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Locale;
import java.util.Set;
Expand Down Expand Up @@ -51,6 +52,10 @@ public class NumberFormatter implements Formatter<Number> {
/** Maintains a set of named formats that can be used instead of patterns. */
protected static final Set<String> namedPatterns = new HashSet<>();

private static final ThreadLocal<HashMap<Locale, NumberFormat>> numberFormatNumberCache = ThreadLocal.withInitial(HashMap::new);
private static final ThreadLocal<HashMap<Locale, NumberFormat>> numberFormatPercentCache = ThreadLocal.withInitial(HashMap::new);
private static final ThreadLocal<HashMap<Locale, NumberFormat>> numberFormatCurrencyCache = ThreadLocal.withInitial(HashMap::new);

static {
namedPatterns.add("plain");
namedPatterns.add("integer");
Expand Down Expand Up @@ -96,16 +101,19 @@ public void init() {
formatPattern = "plain";
}

if ( formatType.equalsIgnoreCase("number") ) {
format = NumberFormat.getInstance(locale);
} else if ( formatType.equalsIgnoreCase("currency") ) {
format = NumberFormat.getCurrencyInstance(locale);
} else if ( formatType.equalsIgnoreCase("percentage") ) {
format = NumberFormat.getPercentInstance(locale);
} else {
throw new StripesRuntimeException(
"Invalid format type supplied for formatting a " + "number: " + formatType + ". Valid values are 'number', 'currency' "
+ "and 'percentage'.");
switch (formatType.toLowerCase()) {
case "number":
format = numberFormatNumberCache.get().computeIfAbsent(locale, NumberFormat::getInstance);
break;
case "currency":
format = numberFormatCurrencyCache.get().computeIfAbsent(locale, NumberFormat::getCurrencyInstance);
break;
case "percentage":
format = numberFormatPercentCache.get().computeIfAbsent(locale, NumberFormat::getPercentInstance);
break;
default:
throw new StripesRuntimeException(
"Invalid format type supplied for formatting a " + "number: " + formatType + ". Valid values are 'number', 'currency' " + "and 'percentage'.");
}

// Do any extra configuration
Expand Down