Custom Serialization

suggest change

This example creates a class that prints a random integer in an inclusive range. The bounds are passed to the constructor.

public class SimpleRangeRandom implements Runnable {
private int min;
private int max;

private Thread thread;

public SimpleRangeRandom(int min, int max){
    this.min = min;
    this.max = max;
    thread = new Thread(this);
    thread.start();
}

@Override
public void run() {
    while(true) {
        Random rand = new Random();
        System.out.println("Thread: " + thread.getId() + " Random:" + (rand.nextInt(max - min + 1) + min));
        try {
            Thread.sleep(10000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}
}

Making this class Serializable fails because Thread is not serializable. Declare the thread transient. The object can then be serialized, but readObject does not run the constructor, so the thread started there is not created again. Custom serialization supplies these exact private methods:

private void writeObject(ObjectOutputStream out) throws IOException;
private void readObject(ObjectInputStream in) throws IOException, ClassNotFoundException;

readObject can create and start the thread after defaultReadObject() restores min and max:

class RangeRandom implements Serializable, Runnable {

private int min;
private int max;

private transient Thread thread;
//transient should be any field that either cannot be serialized e.g Thread or any field you do not want serialized

public RangeRandom(int min, int max){
    this.min = min;
    this.max = max;
    thread = new Thread(this);
    thread.start();
}

@Override
public void run() {
    while(true) {
        Random rand = new Random();
        System.out.println("Thread: " + thread.getId() + " Random:" + (rand.nextInt(max - min + 1) + min));
        try {
            Thread.sleep(10000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}

private void writeObject(ObjectOutputStream oos) throws IOException {
    oos.defaultWriteObject();
}

private void readObject(ObjectInputStream in) throws IOException, ClassNotFoundException {
    in.defaultReadObject();
    thread = new Thread(this);
    thread.start();
}
}

Here is the main for our example:

public class Main {
    public static void main(String[] args) {
        System.out.println("Hello");
        RangeRandom rangeRandom = new RangeRandom(1, 10);

        try (ObjectOutputStream out = new ObjectOutputStream(new FileOutputStream("test"))) {
            out.writeObject(rangeRandom);
        } catch (IOException ex) {
            ex.printStackTrace();
        }

        try (ObjectInputStream in = new ObjectInputStream(new FileInputStream("test"))) {
            RangeRandom rangeRandom2 = (RangeRandom) in.readObject();
        } catch (IOException | ClassNotFoundException ex) {
            ex.printStackTrace();
        }
    }
}

Running main starts one thread in the constructor of the original instance and another in readObject of the deserialized copy. Both threads print numbers. nextInt(max - min + 1) + min covers both endpoints. It throws IllegalArgumentException when max < min.

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents