1 package org.apidesign.apifest08.currency;
4 import java.math.BigDecimal;
5 import java.util.Currency;
6 import java.util.HashMap;
8 import java.util.Timer;
9 import java.util.TimerTask;
13 * Keeps track of the current value for each currency as USD.
15 * @author D'Arcy Smith
21 * The values expressed in USD.
23 private static Map<Currency, BigDecimal> values;
26 * Update the values periodically
28 private static final Timer refresher;
32 final Refresher refresherTask;
35 // load the map NOW! (don't use the scheduler to do it just because we want
36 // to be 100% certain it is loaded before anything else can be called.
39 refresherTask = new Refresher();
40 refresher = new Timer("CurrencyValues Refresher", true);
42 // update once an hour
43 delay = 1000 * 60 * 60;
44 refresher.scheduleAtFixedRate(refresherTask, delay, delay);
48 * Prevent accidental creation.
50 private CurrencyValues()
55 * Refresh the currency values.
59 Map<Currency, BigDecimal> newValues;
62 newValues = new HashMap<Currency, BigDecimal>();
64 // these would update from a data source, database, web service, something...
65 currency = Currency.getInstance("USD");
66 newValues.put(currency, BigDecimal.valueOf(1.0).setScale(2));
68 currency = Currency.getInstance("CZK");
69 newValues.put(currency, BigDecimal.valueOf(17.0));
71 currency = Currency.getInstance("SKK");
72 newValues.put(currency, BigDecimal.valueOf(21.25));
74 // don't sycnhronize all of it because clients can use slightly out of
76 synchronized(CurrencyValues.class)
83 * Get the value of the specified currency in USD.
85 * @param currency the corrency to get.
86 * @return the value of the currency in USD.
87 * @throws IllegalArgumentException if currency is null.
89 static BigDecimal getValue(final Currency currency)
91 final BigDecimal value;
95 throw new IllegalArgumentException("currencyName cannot be null");
98 // make sure we are not updating the map right now
99 synchronized(CurrencyValues.class)
101 value = values.get(currency);
108 * Used to update the currency map periodically.
110 private static class Refresher
114 * call the refresh method.