// Copyright (c) Keith D Gregory, all rights reserved
package com.kdgregory.example.serialization;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;

public class SharedMutableObjectExample
{
    private static class MyMutableObject
    implements Serializable
    {
        private static final long serialVersionUID = 1L;
        private int value;

        public void setValue(int value)
        {
            this.value = value;
        }

        public int getValue()
        {
            return value;
        }
    }


    public static void main(String[] argv)
    throws Exception
    {
        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        ObjectOutputStream oos = new ObjectOutputStream(bos);

        MyMutableObject obj = new MyMutableObject();
        for (int ii = 0 ; ii < 5 ; ii++)
        {
            obj.setValue(ii);
            oos.writeObject(obj);
        }

        oos.close();
        ByteArrayInputStream bis = new ByteArrayInputStream(bos.toByteArray());
        ObjectInputStream ois = new ObjectInputStream(bis);

        for (int ii = 0 ; ii < 5 ; ii++)
        {
            MyMutableObject ret = (MyMutableObject)ois.readObject();
            System.out.println("read #" + ii + " value = " + ret.getValue());
        }
    }
}
