[JAVA] When serialization fails

What to do if serialization fails

Introduction

It's about Java. If you want to serialize an object If you add Serializable to the interface, it will be serialized. However, it is a memo at that time what to do if Serializable is added but it is not serialized.

What is serialization?

In the first place, the serialization process is to convert to a recoverable string. It is used to make it possible to read something that exists only in the memory space, such as Object.

(Details below) https://docs.oracle.com/javase/jp/8/docs/api/java/io/Serializable.html

When you want to retain Object information with Redis etc., serialize it once (of course, you do not need to take the serialization method) It is possible to retain object information by doing so.

When serialization restore fails

However, there is a complicated Object information, and a JDK-type Exception that cannot be serialized occurs, or If unnecessary variable information is serialized and performance is degraded, It is possible to specify the serialization target individually.

At this time, what can be used Externalizable

Will be.


public class HogeModel implements Externalizable {

	/**
	 *Original serialization process
	 *
	 * @param out output stream
	 * @throws IOException IO error
	 */
	@Override
	@SuppressWarnings("resource")
	public void writeExternal(final ObjectOutput out) throws IOException {

		Packer pk = MessagePackManager.getInstance().createPacker((OutputStream) out);

		pk.write(this.hogehoge);
	}


	/**
	 *Original deserialization process
	 *
	 * @param in input stream
	 * @throws IOException IO error
	 */
	@Override
	public void readExternal(final ObjectInput in) throws IOException {
		try {
			@SuppressWarnings("resource")
			Unpacker upk = MessagePackManager.getInstance().createUnpacker((InputStream) in);

			this.hogehoge = upk.readInt();

		} catch (IOException e) {
			throw e;
		} catch (Exception e) { 
			throw new IOException(e);
		}
	}

}

Recommended Posts

When serialization fails
When semantic-ui install fails
Java Object Serialization why & when
Response when Tomcat server startup fails
Java serialization
When the server fails to start in Eclipse