A thread in java can’t be restarted in Java, so I implemented a java Thread , and then tried to restart the thread after getting the serialized object of Thread.
import java.io.Serializable;
public class ThreadSerialization extends Thread implements Serializable {
int iCheck = 10;
@Override
public void run() {
System.out.println("STARTING");
for(int i=0;i<10;i++){
iCheck+=i;
}
}
}
and Serializing algo-
public class CallingThreadSerializable {
public static void main(String[] args) {
ThreadSerialization ser = new ThreadSerialization();
ser.start();
FileOutputStream fos = null;
ObjectOutputStream out = null;
FileInputStream fis = null;
ObjectInputStream ois = null;
try {
fos = new FileOutputStream("thread.ser");
out = new ObjectOutputStream(fos);
out.writeObject(ser);
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
try {
out.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
try {
fis = new FileInputStream("thread.ser");
ois = new ObjectInputStream(fis);
ThreadSerialization ser1 = (ThreadSerialization) ois.readObject();
System.out.println("---> " + ser1.iCheck);
ser1.start();
System.out.println("---> " + ser1.iCheck);
ois.close();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
OUTPUT-
STARTING
---> 55
---> 55
STARTING
Why the ser1 object is starting again ?
If you deserialize(?) an Object then you are essentially creating a new instance of that class with the same properties as the original Object.
It is not the same Object.
As well, since Thread itself doesn’t implement Serializable, startedness is effectively part of the transient state in any Serializable subclass (as is interruptedness), because serialization doesn’t restore fields inherited from a non-Serializable superclass. Any class that
extends Thread implements Serializable, assuming there’s a good reason to do so at all, should probably have its own fields to track startedness and interruptedness, and callThread.start()andThread.interrupt()inreadObject()orreadResolve()to restore those elements of its state.