SimpleDateFormatPool { public static SimpleDateFormat get(String pattern) { Map<String, SimpleDateFormat> map = pool.get(); SimpleDateFormat sdf = map.get(pattern); if (sdf == null) { sdf = new SimpleDateFormat(pattern); sdf.setLenient(false); map.put(pattern, sdf); } return sdf; }  static SimpleDateFormat get(String pattern);  }
@Test public void testGet() { Object[][] tests = { new Object[]{"dd-MM-yyyy", sdf("dd-MM-yyyy")}, new Object[]{"dd.MM.yyyy", sdf("dd.MM.yyyy")}, new Object[]{"yyyy/MM/dd", sdf("yyyy/MM/dd")} }; for (Object[] row : tests) { String pattern = (String) row[0]; SimpleDateFormat expected = (SimpleDateFormat) row[1]; SimpleDateFormat result = new NonAbstractPool().get(pattern); assertEquals(expected, result); } }
@Test public void testGet__cache() { SimpleDateFormat sdf1 = SimpleDateFormatPool.get("dd/MM/yyyy"); SimpleDateFormat sdf2 = SimpleDateFormatPool.get("dd/MM/yyyy"); assertSame(sdf1, sdf2); }
@Test public void testGet__multipleThreads() throws InterruptedException { final List<SimpleDateFormat> list = Collections.synchronizedList(new ArrayList<SimpleDateFormat>()); Thread[] threads = new Thread[10]; for (int i = 0; i < 10; i++) { threads[i] = new Thread(new Runnable() { @Override public void run() { list.add(SimpleDateFormatPool.get("dd-MM-yyyy")); } }); threads[i].start(); } for (int i = 0; i < 10; i++) { threads[i].join(); } for (int i = 0; i < 10; i++) { SimpleDateFormat sdf1 = list.get(i); for (int j = 0; j < 10; j++) { if (j != i) { SimpleDateFormat sdf2 = list.get(j); assertNotSame(sdf1, sdf2); } } } }