Posted In: Caching, Java Core

Do not forget to add serialVersionUID in your POJO

What is a serialVersionUID and why should developer use it in POJO?

Why developer should always add serialVersionUID in POJO.

In an enterprise application sooner than later you will start using some caching mechanism. Any changes in POJO even if very small can change UID. In such cases all your cached objects will not work. Hence always add serialVersionUID to POJO.
Let us create testcase using some Cache. I am using Hazelcast in this example.

Steps

1. Create POJO with few String get set methods. Make sure you do not add serialVersionUID
2. Now add few POJO instances to Hazelcast
3. Run get to check POJOs. It should be successful.
4. Now add simple toString method to POJO. It is not changing any POJO functionality.
5. Now run get again. It will fail with java.io.InvalidClassException. This is happening because Hazelcast is trying to recalculate serialVersionUID for de-serialization.
6. Now repeat steps with POJO with serialVersionUID. All should succeed

Step 1 – Pojo without serialVersionUID

package com.example.java.core;
import java.io.Serializable;
public class Pojo1 implements Serializable {
	private String s1;
	private String s2;

	public String getS1() {
		return s1;
	}

	public void setS1(String s1) {
		this.s1 = s1;
	}

	public String getS2() {
		return s2;
	}

	public void setS2(String s2) {
		this.s2 = s2;
	}
}

Step 2 – Add and get in Hazelcast

package com.example.hazelcast;

import java.util.Map;

import com.example.java.core.Pojo1;
import com.hazelcast.config.Config;
import com.hazelcast.core.Hazelcast;
import com.hazelcast.core.HazelcastInstance;

public class InsertCache {

	private HazelcastInstance instance = null;

	public static void main(String[] args) throws Exception {
		InsertCache insertCache = new InsertCache();
		insertCache.start();
		insertCache.insert();
		insertCache.get();
	}

	private void start() throws Exception {
		System.out.println("start.......");
		Config cfg = new Config();
		instance = Hazelcast.newHazelcastInstance(cfg);
	}

	private void insert() throws Exception {
		System.out.println("insert.......");
		Map<Integer, Pojo1> mapCustomers = instance.getMap("customers");
		mapCustomers.put(1, new Pojo1());
		mapCustomers.put(2, new Pojo1());
		mapCustomers.put(3, new Pojo1());
	}

	private void get() throws Exception {
		System.out.println("get.......");
		Map<Integer, Pojo1> mapCustomers = instance.getMap("customers");
		Pojo1 pojo1 = mapCustomers.get(1);
		pojo1 = mapCustomers.get(2);
		pojo1 = mapCustomers.get(3);
		pojo1 = mapCustomers.get(4);
	}
}

Step 3 – Add toString to POJO

package com.example.java.core;
import java.io.Serializable;
public class Pojo1 implements Serializable {
	private String s1;
	private String s2;
.......

	@Override
	public String toString() {
		return "Pojo1 [s1=" + s1 + ", s2=" + s2 + "]";
	}
}

Step 4 – Run get again

package com.example.hazelcast;

import java.util.Map;

import com.example.java.core.Pojo1;
import com.hazelcast.config.Config;
import com.hazelcast.core.Hazelcast;
import com.hazelcast.core.HazelcastInstance;

public class InsertCache {

	private HazelcastInstance instance = null;

	public static void main(String[] args) throws Exception {
		InsertCache insertCache = new InsertCache();
		insertCache.start();
		//insertCache.insert();
		insertCache.get();
	}
.....
.....
}

Error

Caused by: java.io.InvalidClassException: com.example.java.core.Pojo1; 
local class incompatible: stream classdesc serialVersionUID = -3366797186448136181, 
local class serialVersionUID = 1511969898412467905
	at java.io.ObjectStreamClass.initNonProxy(Unknown Source)
	at java.io.ObjectInputStream.readNonProxyDesc(Unknown Source)
	at java.io.ObjectInputStream.readClassDesc(Unknown Source)
	at java.io.ObjectInputStream.readOrdinaryObject(Unknown Source)
	at java.io.ObjectInputStream.readObject0(Unknown Source)
	at java.io.ObjectInputStream.readObject(Unknown Source)
	at com.hazelcast.internal.serialization.impl.
JavaDefaultSerializers$JavaSerializer.read(JavaDefaultSerializers.java:219)
	at com.hazelcast.internal.serialization.impl.
StreamSerializerAdapter.read(StreamSerializerAdapter.java:48)
	at com.hazelcast.internal.serialization.impl.
AbstractSerializationService.toObject(AbstractSerializationService.java:184)
Description given in java doc
The serialization runtime associates with each serializable class a version number, called a serialVersionUID, which is used during deserialization to verify that the sender and receiver of a serialized object have loaded classes for that object that are compatible with respect to serialization. If the receiver has loaded a class for the object that has a different serialVersionUID than that of the corresponding sender’s class, then deserialization will result in an InvalidClassException. A serializable class can declare its own serialVersionUID explicitly by declaring a field named “serialVersionUID” that must be static, final, and of type long:

ANY-ACCESS-MODIFIER static final long serialVersionUID = 42L;

If a serializable class does not explicitly declare a serialVersionUID, then the serialization runtime will calculate a default serialVersionUID value for that class based on various aspects of the class, as described in the Java(TM) Object Serialization Specification. However, it is strongly recommended that all serializable classes explicitly declare serialVersionUID values, since the default serialVersionUID computation is highly sensitive to class details that may vary depending on compiler implementations, and can thus result in unexpected InvalidClassExceptions during deserialization. Therefore, to guarantee a consistent serialVersionUID value across different java compiler implementations, a serializable class must declare an explicit serialVersionUID value. It is also strongly advised that explicit serialVersionUID declarations use the private modifier where possible, since such declarations apply only to the immediately declaring class–serialVersionUID fields are not useful as inherited members. Array classes cannot declare an explicit serialVersionUID, so they always have the default computed value, but the requirement for matching serialVersionUID values is waived for array classes.

How to add serialVersionUID in Eclipse
Create your POJO and Eclipse will suggest to add ID. Please follow the steps.

Hazelcast setup

Add Hazelcast maven entry to pom.xml

<dependency>
	<groupId>com.hazelcast</groupId>
	<artifactId>hazelcast</artifactId>
	<version>3.8.4</version>
</dependency>

Java code to start Hazelcast instance

import com.hazelcast.config.Config;
import com.hazelcast.core.Hazelcast;
import com.hazelcast.core.HazelcastInstance;
.....
Config cfg = new Config();
HazelcastInstance instance = instance = Hazelcast.newHazelcastInstance(cfg);

by , on August 23rd, 2017

  • Categories