3

これが私の変換コードです。大きなデータを扱っていると、これには長い時間がかかります... メソッドをほぼ 100 万回呼び出します... しばらくスレッドを保持していることがはっきりとわかりました。

パフォーマンスを向上させる方法を教えてください。

public class GenericObjectXMLConverter<T> {

  private T t = null;
  private static JAXBContext jaxbContext =null;
  public GenericObjectXMLConverter() {

  }
  public GenericObjectXMLConverter(T obj){
    t = obj;
  }

  protected final Logger  log = Logger.getLogger(getClass());

  /**
   * Converts the java Object and into a xml string message type.
   * @param object the object to convert
   * @return String the converted xml message as string
   */
  public String objectToXMLMessage(T object) {
    StringWriter stringWriter = new StringWriter();
    //JAXBContext jaxbContext=null;
    try {
      jaxbContext = JAXBContext.newInstance(object.getClass());
      Marshaller jaxbMarshaller = jaxbContext.createMarshaller();
      jaxbMarshaller.marshal(object, stringWriter);
    } catch (JAXBException e) {
      log.warn("JAXBException occured while converting the java object into xml string :"+e.getMessage());
    }
       /*if(log.isDebugEnabled())
         log.debug("xml string after conversion:"+stringWriter.toString());*/
       return stringWriter.toString();
  }

  /**
   * Converts a xml string message into a Java Object
   * @param string the string message to convert
   * @return Object the result as Java Object. If the message parameter is null then
     *  this method will simply return null.
   */
  @SuppressWarnings("unchecked")
  public T xmlToObject(String message) {
    if(message.equals("") || message.equals(" ") || message.length()==0){
      return null;
    }else{
      T object=null;
      try {
        jaxbContext = JAXBContext.newInstance(t.getClass());
        StringReader reader = new StringReader(message);
        Unmarshaller jaxbUnmarshaller = jaxbContext.createUnmarshaller();
        object = (T)jaxbUnmarshaller.unmarshal(reader);
        } catch (JAXBException e) {
        log.warn("JAXBException occured while converting the xml string into a Java Object :"+e.getMessage());
        }
       /* if(log.isDebugEnabled()){
          log.debug("Java object after conversion:"+object.toString());
        }*/
      return object;
    }
  }

}
4

2 に答える 2

19

パフォーマンス クラスと JAXB ランタイム クラス

  • JAXBContext同じものを何度も 作成することは避けてください。JAXBContextはスレッドセーフであり、パフォーマンスを向上させるために再利用する必要があります。
  • Marshaller/Unmarshallerはスレッド セーフではありませんが、すばやく作成できます。それらを再利用することはそれほど大したことではありません。
于 2013-09-04T09:43:56.173 に答える