Tôi thường giải quyết các vấn đề như thế này với mẫu lớp học ThreadLocal
. Với thực tế là bạn cần một marshaller khác nhau cho mỗi Class, bạn có thể kết hợp nó với một mẫu singleton
-map.
Để giúp bạn tiết kiệm 15 phút, công việc. Sau đây tôi thực hiện một nhà máy an toàn cho Jaxb Marshallers và Unmarshallers.
Nó cho phép bạn truy cập các trường hợp như sau ...
Marshaller m = Jaxb.get(SomeClass.class).getMarshaller();
Unmarshaller um = Jaxb.get(SomeClass.class).getUnmarshaller();
Và mã bạn sẽ cần phải là một lớp JAXB nhỏ mà trông như sau:
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;
}
}
câu trả lời hay. Bây giờ tôi có thể tự tin dựa trên kinh nghiệm của bạn với tư cách là khách hàng tiềm năng trên JAXB. – Vladimir
Tôi tin tưởng bạn, nhưng điều này có được tìm thấy ở đâu đó trong tài liệu không? – Hurda
Tài liệu dành cho RI: https://jaxb.java.net/guide/Performance_and_thread_safety.html (nhưng không phải Moxy AFAIK) – Caoilte