KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > com > openedit > util > XmlWriterPool


1 /*
2  * Created on Aug 2, 2006
3  */

4 package com.openedit.util;
5
6 import java.io.UnsupportedEncodingException JavaDoc;
7 import java.util.HashMap JavaDoc;
8 import java.util.Map JavaDoc;
9
10 import org.dom4j.io.OutputFormat;
11 import org.dom4j.io.XMLWriter;
12
13 import com.openedit.OpenEditRuntimeException;
14
15 public class XmlWriterPool
16 {
17     protected ThreadLocal JavaDoc perThreadCache = new ThreadLocal JavaDoc();
18
19     public XmlWriterPool() {
20     }
21
22     public void reset() {
23         perThreadCache = new ThreadLocal JavaDoc();
24     }
25
26     public XMLWriter instance(String JavaDoc inEncoding) {
27         Map JavaDoc ref = (Map JavaDoc) perThreadCache.get();
28         if( ref == null)
29         {
30             ref = new HashMap JavaDoc();
31             // use weak reference to prevent cyclic reference during GC
32
perThreadCache.set(ref);
33         }
34         XMLWriter singletonInstancePerThread = (XMLWriter)ref.get(inEncoding);
35         
36         if ( singletonInstancePerThread == null )
37         {
38             OutputFormat format = OutputFormat.createPrettyPrint();
39             format.setEncoding(inEncoding); //this is annoying since we can only set it once per thread
40

41             try
42             {
43                 singletonInstancePerThread = new XMLWriter(format);
44             }
45             catch (UnsupportedEncodingException JavaDoc ex)
46             {
47                 throw new OpenEditRuntimeException();
48             }
49             ref.put(inEncoding, singletonInstancePerThread);
50         }
51         return singletonInstancePerThread;
52     }
53 }
54     
55
56
Popular Tags