मैं आमतौर पर एक ThreadLocal
वर्ग पैटर्न के साथ इस तरह की समस्याओं को हल। इस तथ्य को देखते हुए कि आपको प्रत्येक कक्षा के लिए एक अलग मार्शलर की आवश्यकता है, आप इसे singleton
-map पैटर्न के साथ जोड़ सकते हैं।
आपको 15 मिनट का काम बचाने के लिए। जैक्सब मार्शलर्स और अनमारशैलर्स के लिए थ्रेड-सुरक्षित फैक्ट्री के कार्यान्वयन के बाद यहां दिया गया है।
यह आपको निम्नानुसार उदाहरणों तक पहुंचने की अनुमति देता है ...
Marshaller m = Jaxb.get(SomeClass.class).getMarshaller();
Unmarshaller um = Jaxb.get(SomeClass.class).getUnmarshaller();
और कोड आप की आवश्यकता होगी एक छोटे से JAXB वर्ग कि इस प्रकार दिखाई देता है:
public class Jaxb
{
// singleton pattern: one instance per class.
private static Map<Class,Jaxb> singletonMap = new HashMap<>();
private Class clazz;
// thread-local pattern: one marshaller/unmarshaller instance per thread
private ThreadLocal<Marshaller> marshallerThreadLocal = new ThreadLocal<>();
private ThreadLocal<Unmarshaller> unmarshallerThreadLocal = new ThreadLocal<>();
// The static singleton getter needs to be thread-safe too,
// so this method is marked as synchronized.
public static synchronized Jaxb get(Class clazz)
{
Jaxb jaxb = singletonMap.get(clazz);
if (jaxb == null)
{
jaxb = new Jaxb(clazz);
singletonMap.put(clazz, jaxb);
}
return jaxb;
}
// the constructor needs to be private,
// because all instances need to be created with the get method.
private Jaxb(Class clazz)
{
this.clazz = clazz;
}
/**
* Gets/Creates a marshaller (thread-safe)
* @throws JAXBException
*/
public Marshaller getMarshaller() throws JAXBException
{
Marshaller m = marshallerThreadLocal.get();
if (m == null)
{
JAXBContext jc = JAXBContext.newInstance(clazz);
m = jc.createMarshaller();
marshallerThreadLocal.set(m);
}
return m;
}
/**
* Gets/Creates an unmarshaller (thread-safe)
* @throws JAXBException
*/
public Unmarshaller getUnmarshaller() throws JAXBException
{
Unmarshaller um = unmarshallerThreadLocal.get();
if (um == null)
{
JAXBContext jc = JAXBContext.newInstance(clazz);
um = jc.createUnmarshaller();
unmarshallerThreadLocal.set(um);
}
return um;
}
}
महान उत्तर। मैं अब JAXB पर लीड के रूप में अपने अनुभव के आधार पर आत्मविश्वास रख सकता हूं। – Vladimir
मैं आपको भरोसा करता हूं, लेकिन क्या यह कहीं दस्तावेज़ीकरण में पाया जा सकता है? – Hurda
यह आरआई के लिए प्रलेखित है: https://jaxb.java.net/guide/Performance_and_thread_safety.html (लेकिन मोक्सी AFAIK नहीं) – Caoilte