что делает метод reset в классе objectoutputstream java
Что делает метод reset в классе objectoutputstream java
Только объекты, которые поддерживают java.io. Сериализуемый интерфейс может быть записан потокам. Класс каждого сериализуемого объекта кодируется включая имя класса и подпись класса, значения полей объекта и массивов, и закрытия любых других объектов, на которые ссылаются от начальных объектов.
Метод writeObject используется, чтобы записать объект в поток. Любой объект, включая Строки и массивы, пишется с writeObject. Многократные объекты или примитивы могут быть записаны потоку. Объекты должны быть считаны назад из соответствующего ObjectInputstream с теми же самыми типами и в том же самом порядке, как они были записаны.
Примитивные типы данных могут также быть записаны потоку, используя соответствующие методы от DataOutput. Строки могут также быть записаны, используя writeUTF метод.
Механизм сериализации по умолчанию для объекта пишет класс объекта, подписи класса, и значений всех непереходных и нестатических полей. Ссылки на другие объекты (кроме в переходных или статических полях) заставляют те объекты быть записанными также. Многократные ссылки на единственный объект кодируются, используя ссылочный механизм разделения доступа так, чтобы графики объектов могли быть восстановлены той же самой форме как тогда, когда оригинал был записан.
Например, чтобы записать объект, который может быть считан примером в ObjectInputStream:
Классы, которые требуют специальной обработки во время сериализации и процесса десериализации, должны реализовать специальные методы с этими точными подписями:
writeObject метод ответственен за запись состояния объекта для его определенного класса так, чтобы соответствующий readObject метод мог восстановить это. Метод не должен интересоваться состоянием, принадлежащим суперклассам объекта или подклассам. Государство сохраняется при записи отдельных полей в ObjectOutputStream, используя writeObject метод или при использовании методов для примитивных типов данных, поддерживаемых DataOutput.
Сериализация объекта может быть предотвращена, реализовывая writeObject и readObject методы, которые бросают NotSerializableException. Исключение будет поймано ObjectOutputStream и прервет процесс сериализации.
Примитивные данные, исключая сериализуемые поля и externalizable данные, пишутся ObjectOutputStream в блочных записях данных. Блочная запись данных составляется из заголовка и данных. Блочный заголовок данных состоит из маркера и числа байтов, чтобы следовать за заголовком. Последовательные примитивные записи данных объединяются в одну блочную запись данных. Число записей в блоке, используемое для блочной записи данных, составит 1024 байта. Каждая блочная запись данных будет заполнена до 1024 байтов, или будет записана всякий раз, когда есть завершение блочного режима данных. Звонки в методы ObjectOutputStream writeObject, defaultWriteObject и writeFields первоначально завершают любую существующую блочную запись данных.
Что делает метод reset в классе objectoutputstream java
Only objects that support the java.io.Serializable interface can be written to streams. The class of each serializable object is encoded including the class name and signature of the class, the values of the object’s fields and arrays, and the closure of any other objects referenced from the initial objects.
The method writeObject is used to write an object to the stream. Any object, including Strings and arrays, is written with writeObject. Multiple objects or primitives can be written to the stream. The objects must be read back from the corresponding ObjectInputstream with the same types and in the same order as they were written.
Primitive data types can also be written to the stream using the appropriate methods from DataOutput. Strings can also be written using the writeUTF method.
The default serialization mechanism for an object writes the class of the object, the class signature, and the values of all non-transient and non-static fields. References to other objects (except in transient or static fields) cause those objects to be written also. Multiple references to a single object are encoded using a reference sharing mechanism so that graphs of objects can be restored to the same shape as when the original was written.
For example to write an object that can be read by the example in ObjectInputStream:
Classes that require special handling during the serialization and deserialization process must implement special methods with these exact signatures:
The writeObject method is responsible for writing the state of the object for its particular class so that the corresponding readObject method can restore it. The method does not need to concern itself with the state belonging to the object’s superclasses or subclasses. State is saved by writing the individual fields to the ObjectOutputStream using the writeObject method or by using the methods for primitive data types supported by DataOutput.
Serialization does not write out the fields of any object that does not implement the java.io.Serializable interface. Subclasses of Objects that are not serializable can be serializable. In this case the non-serializable class must have a no-arg constructor to allow its fields to be initialized. In this case it is the responsibility of the subclass to save and restore the state of the non-serializable class. It is frequently the case that the fields of that class are accessible (public, package, or protected) or that there are get and set methods that can be used to restore the state.
Serialization of an object can be prevented by implementing writeObject and readObject methods that throw the NotSerializableException. The exception will be caught by the ObjectOutputStream and abort the serialization process.
Implementing the Externalizable interface allows the object to assume complete control over the contents and format of the object’s serialized form. The methods of the Externalizable interface, writeExternal and readExternal, are called to save and restore the objects state. When implemented by a class they can write and read their own state using all of the methods of ObjectOutput and ObjectInput. It is the responsibility of the objects to handle any versioning that occurs.
Enum constants are serialized differently than ordinary serializable or externalizable objects. The serialized form of an enum constant consists solely of its name; field values of the constant are not transmitted. To serialize an enum constant, ObjectOutputStream writes the string returned by the constant’s name method. Like other serializable or externalizable objects, enum constants can function as the targets of back references appearing subsequently in the serialization stream. The process by which enum constants are serialized cannot be customized; any class-specific writeObject and writeReplace methods defined by enum types are ignored during serialization. Similarly, any serialPersistentFields or serialVersionUID field declarations are also ignored—all enum types have a fixed serialVersionUID of 0L.
Primitive data, excluding serializable fields and externalizable data, is written to the ObjectOutputStream in block-data records. A block data record is composed of a header and data. The block data header consists of a marker and the number of bytes to follow the header. Consecutive primitive data writes are merged into one block-data record. The blocking factor used for a block-data record will be 1024 bytes. Each block-data record will be filled up to 1024 bytes, or be written whenever there is a termination of block-data mode. Calls to the ObjectOutputStream methods writeObject, defaultWriteObject and writeFields initially terminate any existing block-data record.
Разница между flush () и reset () в JAVA
3 ответа
Почему используется метод сброса, если кэш памяти очищается методом очистки?
Сброс будет игнорировать состояние любых объектов, уже записанных в поток.
Объекты, ранее записанные в поток, не будут упоминаться как уже находящиеся в потоке. Они будут снова записаны в поток.
Эти детали важны, поскольку ObjectOutputStream использует механизм совместного использования ссылок.
Поэтому запись в поток несколько раз одного и того же объекта, но с другим состоянием, приведет к записи объекта с исходным состоянием несколько раз.
Документация верхнего уровня ObjectOutputStream объясняет, что и еще (акцент мой):
Пример, иллюстрирующий проблему с кешем ObjectOutputStream :
Выполните этот класс, который пишет 10 раз один и тот же объект, но с другим состоянием i nan ObjectOutputStream без вызова reset() между записями:
С Foo определяется как:
По мере ознакомления с содержанием ЛС вы получите:
Раскомментируйте reset() и вы увидите изменения:
Сброс () будет игнорировать состояние любых объектов, уже записанных в поток. Состояние сбрасывается, чтобы быть таким же, как новый ObjectOutputStream. Текущая точка в потоке помечена как сброшенная, поэтому соответствующий ObjectInputStream будет сброшен в той же точке. Объекты, ранее записанные в поток, не будут считаться уже находящимися в потоке. Они будут снова записаны в поток.
Метод flush () очищает поток. Это записывает любые буферизованные выходные байты и сбрасывает их в основной поток.
Метод flush() будет очищать буфер и записывать в поток, а reset() будет использоваться для изменения объектов, которые уже были записаны в поток.
reset() сделает недействительными все отправленные объекты. При повторной отправке неизмененных объектов передается только ссылка, позволяющая повторно использовать кэшированную версию уже переданного объекта. Это гораздо эффективнее, чем всегда отправлять весь объект.
С другой стороны, flush() будет только следить за тем, чтобы данные действительно записывались в поток. Операция записи только помещает данные в буфер и может записывать их в поток в зависимости от размера буфера. Вызов flush() гарантирует, что данные будут записаны в поток. Но flush не очистит кэшированные объекты.
Что делает метод reset в классе objectoutputstream java
Войти
Авторизуясь в LiveJournal с помощью стороннего сервиса вы принимаете условия Пользовательского соглашения LiveJournal
Повторная запись объектов в поток
Очень часто встречается в последнее время проблема: пишут объект в поток, меняют, пишут снова – а на выходе при чтении получают два одинаковых объекта. Первых. Изменения, сделанные перед второй записью, не передаются. Что делать?
На самом деле так оно и должно быть. По следующей причине.
И вот тут-то как раз и есть подводный камень. ObjectOuputStream контролирует ссылочную целостность графа. Иначе говоря, сравнивает он ссылки. И если мы запишем объект, а потом изменим его – ObjectOuputStream об этом изменении не узнает и сочтет объект тем же самым, который он уже записал.
Иллюстрируется это просто:
В результате выполнения этого кода мы получим:
Какие есть варианты действий в такой ситуации?
Первый, самый простой – каждый раз создавать новый объект для записи, вместо модификации существующего. Это, естественно, будет работать. В коде выше это первая закомментированная строка. Убираем комментарий – и тут же получаем:
Второй способ менее тривиален. Заключается он в использовании метода reset() класса ObjectOuputStream (вторая закомментированная строка в коде). Метод этот, как сказано в документации (http://docs.oracle.com/javase/6/docs/api/java/io/ObjectOutputStream.html#reset()):
Reset will disregard the state of any objects already written to the stream. The state is reset to be the same as a new ObjectOutputStream. The current point in the stream is marked as reset so the corresponding ObjectInputStream will be reset at the same point. Objects previously written to the stream will not be refered to as already being in the stream. They will be written to the stream again.
Если мы НЕ используем reset и не пересоздаем объект D. Записываем D. Записываем A, по ссылке записывается и C. Потом модифицируем D. Записываем его – в поток попадает только ссылка на уже записанный объект D. Записываем B, он ссылается на C, который уже записан по ссылке из А. Таким образом, мы сохраняем ссылочную целостность между A, B и C, но теряем изменения в D.
Что делает метод reset в классе objectoutputstream java
Only objects that support the java.io.Serializable interface can be written to streams. The class of each serializable object is encoded including the class name and signature of the class, the values of the object’s fields and arrays, and the closure of any other objects referenced from the initial objects.
The method writeObject is used to write an object to the stream. Any object, including Strings and arrays, is written with writeObject. Multiple objects or primitives can be written to the stream. The objects must be read back from the corresponding ObjectInputstream with the same types and in the same order as they were written.
Primitive data types can also be written to the stream using the appropriate methods from DataOutput. Strings can also be written using the writeUTF method.
The default serialization mechanism for an object writes the class of the object, the class signature, and the values of all non-transient and non-static fields. References to other objects (except in transient or static fields) cause those objects to be written also. Multiple references to a single object are encoded using a reference sharing mechanism so that graphs of objects can be restored to the same shape as when the original was written.
For example to write an object that can be read by the example in ObjectInputStream:
Classes that require special handling during the serialization and deserialization process must implement special methods with these exact signatures:
The writeObject method is responsible for writing the state of the object for its particular class so that the corresponding readObject method can restore it. The method does not need to concern itself with the state belonging to the object’s superclasses or subclasses. State is saved by writing the individual fields to the ObjectOutputStream using the writeObject method or by using the methods for primitive data types supported by DataOutput.
Serialization does not write out the fields of any object that does not implement the java.io.Serializable interface. Subclasses of Objects that are not serializable can be serializable. In this case the non-serializable class must have a no-arg constructor to allow its fields to be initialized. In this case it is the responsibility of the subclass to save and restore the state of the non-serializable class. It is frequently the case that the fields of that class are accessible (public, package, or protected) or that there are get and set methods that can be used to restore the state.
Serialization of an object can be prevented by implementing writeObject and readObject methods that throw the NotSerializableException. The exception will be caught by the ObjectOutputStream and abort the serialization process.
Implementing the Externalizable interface allows the object to assume complete control over the contents and format of the object’s serialized form. The methods of the Externalizable interface, writeExternal and readExternal, are called to save and restore the objects state. When implemented by a class they can write and read their own state using all of the methods of ObjectOutput and ObjectInput. It is the responsibility of the objects to handle any versioning that occurs.
Enum constants are serialized differently than ordinary serializable or externalizable objects. The serialized form of an enum constant consists solely of its name; field values of the constant are not transmitted. To serialize an enum constant, ObjectOutputStream writes the string returned by the constant’s name method. Like other serializable or externalizable objects, enum constants can function as the targets of back references appearing subsequently in the serialization stream. The process by which enum constants are serialized cannot be customized; any class-specific writeObject and writeReplace methods defined by enum types are ignored during serialization. Similarly, any serialPersistentFields or serialVersionUID field declarations are also ignored—all enum types have a fixed serialVersionUID of 0L.
Primitive data, excluding serializable fields and externalizable data, is written to the ObjectOutputStream in block-data records. A block data record is composed of a header and data. The block data header consists of a marker and the number of bytes to follow the header. Consecutive primitive data writes are merged into one block-data record. The blocking factor used for a block-data record will be 1024 bytes. Each block-data record will be filled up to 1024 bytes, or be written whenever there is a termination of block-data mode. Calls to the ObjectOutputStream methods writeObject, defaultWriteObject and writeFields initially terminate any existing block-data record.