1 package com.thoughtworks.xstream.converters.basic; 2 3 import java.text.DateFormat ; 4 import java.text.ParseException ; 5 import java.text.SimpleDateFormat ; 6 import java.util.Date ; 7 8 24 public class ThreadSafeSimpleDateFormat { 25 26 private String formatString; 27 private DateFormat [] pool; 28 private int nextAvailable = 0; 29 30 public ThreadSafeSimpleDateFormat(String format, int initialPoolSize, int maxPoolSize) { 31 this.formatString = format; 32 nextAvailable = -1; 33 pool = new DateFormat [maxPoolSize]; 34 for (int i = 0; i < initialPoolSize; i++) { 35 putInPool(createNew()); 36 } 37 } 38 39 public String format(Date date) { 40 DateFormat format = fetchFromPool(); 41 try { 42 return format.format(date); 43 } finally { 44 putInPool(format); 45 } 46 } 47 48 public Date parse(String date) throws ParseException { 49 DateFormat format = fetchFromPool(); 50 try { 51 return format.parse(date); 52 } finally { 53 putInPool(format); 54 } 55 } 56 57 private DateFormat fetchFromPool() { 58 DateFormat result; 59 synchronized (pool) { 60 while (nextAvailable < 0) { 61 try { 62 pool.wait(); 63 } catch (InterruptedException e) { 64 throw new RuntimeException ("Interrupted whilst waiting " + 65 "for a free item in the pool : " + e.getMessage()); 66 } 67 } 68 result = pool[nextAvailable]; 69 nextAvailable--; 70 } 71 if (result == null) { 72 result = createNew(); 73 putInPool(result); 74 } 75 return result; 76 } 77 78 private void putInPool(DateFormat format) { 79 synchronized (pool) { 80 nextAvailable++; 81 pool[nextAvailable] = format; 82 pool.notify(); 83 } 84 } 85 86 private DateFormat createNew() { 87 return new SimpleDateFormat (formatString); 88 } 89 90 } 91 | Popular Tags |