Uploaded image for project: 'JDK'
  1. JDK
  2. JDK-8075619

Serialization of the java.net.URL is incorrect

XMLWordPrintable

    • Icon: Bug Bug
    • Resolution: Won't Fix
    • Icon: P4 P4
    • None
    • 1.1fcs, 9
    • core-libs

      The serialized form of the j.n.URL includes the hashCode field.
      Initially this field has value -1. Serialized form of the URL object will contain the hashCode field with the value -1.

      When the hashCode() method is called in a first time, the hash code calculated and the result is set to the field. Serialized form of this URL object will contain the hashCode field with the value different from -1.

      The following mini test shows that serialization of the one URL object will result in the different byte arrays:
      ------------------------------------------------------------------
          public static void main(String[] args) throws IOException, ClassNotFoundException {
              URL url = new URL("http://oracle.com");
              byte[] bytes1 = ser(url);
              url.hashCode();
              byte[] bytes2 = ser(url);
              System.out.println(Arrays.equals(bytes1, bytes2));
          }

          private static byte[] ser(URL url) throws IOException, ClassNotFoundException {
              try (ByteArrayOutputStream baos = new ByteArrayOutputStream();
                  ObjectOutputStream oos = new ObjectOutputStream(baos)) {
                  oos.writeObject(url);
                  return baos.toByteArray();
              }
          }
      ------------------------------------------------------------------

      Output will be:
      ------------------------------------------------------------------
      false
      ------------------------------------------------------------------

      Serialization/deserialization via RI won't cause and error, because once deserialized hashCode field will have value -1, it will be calculated when hashCode() method will be called.
      However, it can cause errors during serialization/deserialization via different implementations.

      Tested with JDK9 b53.
      Failed JCK tests is under development.

            msheppar Mark Sheppard
            evotchen Elena Votchennikova (Inactive)
            Votes:
            0 Vote for this issue
            Watchers:
            5 Start watching this issue

              Created:
              Updated:
              Resolved: