SerializedObject.java
Upload User: rhdiban
Upload Date: 2013-08-09
Package Size: 15085k
Code Size: 7k
Category:

Windows Develop

Development Platform:

Java

  1. /*
  2.  *    This program is free software; you can redistribute it and/or modify
  3.  *    it under the terms of the GNU General Public License as published by
  4.  *    the Free Software Foundation; either version 2 of the License, or
  5.  *    (at your option) any later version.
  6.  *
  7.  *    This program is distributed in the hope that it will be useful,
  8.  *    but WITHOUT ANY WARRANTY; without even the implied warranty of
  9.  *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
  10.  *    GNU General Public License for more details.
  11.  *
  12.  *    You should have received a copy of the GNU General Public License
  13.  *    along with this program; if not, write to the Free Software
  14.  *    Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
  15.  */
  16. /*
  17.  *    SerializedObject.java
  18.  *    Copyright (C) 2000 Webmind Inc.
  19.  *
  20.  */
  21. package weka.core;
  22. import java.io.BufferedInputStream;
  23. import java.io.BufferedOutputStream;
  24. import java.io.ByteArrayInputStream;
  25. import java.io.ByteArrayOutputStream;
  26. import java.io.InputStream;
  27. import java.io.ObjectInputStream;
  28. import java.io.ObjectOutputStream;
  29. import java.io.OutputStream;
  30. import java.io.Serializable;
  31. import java.util.zip.GZIPInputStream;
  32. import java.util.zip.GZIPOutputStream;
  33. /**
  34.  * This class stores an object serialized in memory. It allows compression,
  35.  * to be used to conserve memory (for example, when storing large strings
  36.  * in memory), or can be used as a mechanism for deep copying objects.
  37.  *
  38.  * @author Len Trigg (len@intelligenesis.net)
  39.  * @version $Revision: 1.4 $
  40.  */
  41. public class SerializedObject implements Serializable {
  42.   /** Stores the serialized object */
  43.   private byte [] m_Serialized;
  44.   /** True if the object has been compressed during storage */
  45.   private boolean m_Compressed;
  46.   /**
  47.    * Serializes the supplied object into a byte array without compression.
  48.    *
  49.    * @param obj the Object to serialize.
  50.    * @exception Exception if the object is not Serializable.
  51.    */
  52.   public SerializedObject(Object obj) throws Exception {
  53.     this(obj, false);
  54.   }
  55.   /**
  56.    * Serializes the supplied object into a byte array.
  57.    *
  58.    * @param obj the Object to serialize.
  59.    * @param compress true if the object should be stored compressed.
  60.    * @exception Exception if the object is not Serializable.
  61.    */
  62.   public SerializedObject(Object obj, boolean compress) throws Exception {
  63.     //System.err.print("."); System.err.flush();
  64.     m_Compressed = compress;
  65.     m_Serialized = toByteArray(obj, m_Compressed);
  66.   }
  67.   /**
  68.    * Serializes the supplied object to a byte array.
  69.    *
  70.    * @param obj the Object to serialize
  71.    * @param compress true if the object should be compressed.
  72.    * @return the byte array containing the serialized object.
  73.    * @exception Exception if the object is not Serializable.
  74.    */
  75.   protected static byte [] toByteArray(Object obj, boolean compress) 
  76.     throws Exception {
  77.     ByteArrayOutputStream bo = new ByteArrayOutputStream();
  78.     OutputStream os = bo;
  79.     if (compress) {
  80.       os = new GZIPOutputStream(os);
  81.     }
  82.     os = new BufferedOutputStream(os);
  83.     ObjectOutputStream oo = new ObjectOutputStream(os);
  84.     oo.writeObject(obj);
  85.     oo.close();
  86.     return bo.toByteArray();
  87.   }
  88.   /**
  89.    * Gets the object stored in this SerializedObject. The object returned
  90.    * will be a deep copy of the original stored object.
  91.    *
  92.    * @return the deserialized Object.
  93.    */
  94.   public Object getObject() {
  95.     try {
  96.       InputStream is = new ByteArrayInputStream(m_Serialized);
  97.       if (m_Compressed) {
  98.         is = new GZIPInputStream(is);
  99.       }
  100.       is = new BufferedInputStream(is);
  101.       ObjectInputStream oi = new ObjectInputStream(is);
  102.       Object result = oi.readObject();
  103.       oi.close();
  104.       return result;
  105.     } catch (Exception ex) {
  106.       ex.printStackTrace();
  107.     }
  108.     return null;
  109.   }
  110.   /**
  111.    * Compares this object with another for equality.
  112.    *
  113.    * @param other the other Object.
  114.    * @return true if the objects are equal.
  115.    */
  116.   public final boolean equals(Object other) {
  117.     // Check class type
  118.     if ((other == null) || !(other.getClass().equals(this.getClass()))) {
  119.       return false;
  120.     }
  121.     // Check serialized length
  122.     byte [] os = ((SerializedObject)other).m_Serialized;
  123.     if (os.length != m_Serialized.length) {
  124.       return false;
  125.     }
  126.     // Check serialized contents
  127.     for (int i = 0; i < m_Serialized.length; i++) {
  128.       if (m_Serialized[i] != os[i]) {
  129.         return false;
  130.       }
  131.     }
  132.     return true;
  133.   }
  134.   /**
  135.    * Returns a hashcode for this object.
  136.    *
  137.    * @return the hashcode for this object.
  138.    */
  139.   public final int hashCode() {
  140.     
  141.     return m_Serialized.length;
  142.   }
  143.   /**
  144.    * Returns a text representation of the state of this object.
  145.    *
  146.    * @return a String representing this object.
  147.    */
  148.   public String toString() {
  149.     
  150.     return (m_Compressed ? "Compressed object: " : "Uncompressed object: ")
  151.       + m_Serialized.length + " bytes";
  152.   }
  153.   /**
  154.    * Test routine, reads text from stdin and measures memory usage
  155.    */
  156.   public static void main2(String []args) {
  157.     try {
  158.       Runtime r = Runtime.getRuntime();
  159.       r.gc();
  160.       java.io.LineNumberReader lnr = new java.io.LineNumberReader(new java.io.InputStreamReader(System.in));
  161.       StringBuffer sb = new StringBuffer();
  162.       String line;
  163.       while ((line = lnr.readLine()) != null) {
  164.         sb.append(line).append('n');
  165.       }
  166.       String text = sb.toString();
  167.       //System.err.println("TEXT:");
  168.       //System.err.println(text);
  169.       r.gc();
  170.       System.err.print("TOTAL: " + r.totalMemory());
  171.       System.err.println("tFREE: " + r.freeMemory());
  172.       long used = r.totalMemory() - r.freeMemory();
  173.       
  174.       // convert to a compressedobject
  175.       SerializedObject co = new SerializedObject(text, true);
  176.       System.err.print("TOTAL: " + r.totalMemory());
  177.       System.err.println("tFREE: " + r.freeMemory());
  178.       r.gc();
  179.       long used1 = r.totalMemory() - r.freeMemory();
  180.       long csize = used1 - used;
  181.       System.err.println("CompressedSize = " + csize);
  182.       String newstr = (String)co.getObject();
  183.       r.gc();
  184.       System.err.print("TOTAL: " + r.totalMemory());
  185.       System.err.println("tFREE: " + r.freeMemory());
  186.       long used2 = r.totalMemory() - r.freeMemory();
  187.       long usize = used2 - used1;
  188.       System.err.println("UncompressedSize = " + usize);
  189.       // A couple of references to the original objects
  190.       // so they don't get freed prematurely and muck up the
  191.       // measurements.
  192.       newstr = newstr.toLowerCase();
  193.       text = text.toLowerCase();
  194.       System.err.println("Byte array: " + co.toString());
  195.       System.err.println("Length of text: " + text.length());
  196.     } catch (Exception ex) {
  197.       ex.printStackTrace();
  198.     }
  199.   }
  200.   /**
  201.    * Test routine, reads an arff file from stdin and measures memory usage
  202.    * (the arff file should have long string attribute values)
  203.    */
  204.   public static void main(String []args) {
  205.     try {
  206.       Runtime r = Runtime.getRuntime();
  207.       r.gc();
  208.       System.err.print("TOTAL: " + r.totalMemory());
  209.       System.err.println("tFREE: " + r.freeMemory());
  210.       long used = r.totalMemory() - r.freeMemory();
  211.       Instances inst = new Instances(new java.io.BufferedReader(new java.io.InputStreamReader(System.in)));
  212.       r.gc();
  213.       long used1 = r.totalMemory() - r.freeMemory();
  214.       long csize = used1 - used;
  215.       System.err.print("nTOTAL: " + r.totalMemory());
  216.       System.err.println("tFREE: " + r.freeMemory());
  217.       System.err.println("size = " + csize);
  218.       int blah = inst.numAttributes();
  219.     } catch (Exception ex) {
  220.       ex.printStackTrace();
  221.     }
  222.   }
  223. }