Happo
Happo

Reputation: 1397

Methods for Serialization never called

i need to serialize data from a static HashMap. I need this static data because i have no instance of the class in which this map exist. I implement the serializable interface and build this two methods:

private synchronized void writeObject( ObjectOutputStream out ) throws IOException
{
    System.out.println("start serialization ...");

    Collection<TaskUpdateListener> tasks = listeners.values();
    out.writeInt( tasks.size() );
    for(TaskUpdateListener task : tasks)
    {
        out.writeObject( task );
    }   
}

private synchronized void readObject( ObjectInputStream in ) throws IOException, ClassNotFoundException
{
    System.out.println("start deserialization ...");

    int size = in.readInt();
    for( int index = 0; index < size; index++)
    {
        addTaskUpdateListener( (ComponentScheduleTable) in.readObject() );
    }   
}

But this methods are never called. Has anybody the same problem or a solution for this one?

Upvotes: 0

Views: 139

Answers (3)

user207421
user207421

Reputation: 310909

I need this static data because i have no instance of the class in which this map exist.

That makes no sense. If you don't have an instance you can't get the map so you can't serialize it, and if the instance doesn't exist neither does the map.

Howver if you do magically have a reference to the map somehow, just serialize it, you don't need to write any readObject/writeObject methods to do so. Just call ObjectOutputStream.writeObject() with the map as argument, etc.

Upvotes: 0

Aaron Digulla
Aaron Digulla

Reputation: 328614

Drop the synchronized; the methods must be thread safe without this. If you need synchronization, you must implement it differently (for example with locks) to avoid deadlocks.

[EDIT] There can be two reasons why the methods are not called:

  1. The signature isn't 100% correct

  2. These instances are always marked as transient

Upvotes: 1

Andrzej Jozwik
Andrzej Jozwik

Reputation: 14649

Try

private  void writeObject( ObjectOutputStream out ) throws IOException
    {

        System.out.println("start serialization ...");

        Collection<TaskUpdateListener> tasks = listeners.values();
        out.writeInt( tasks.size() );
        for(TaskUpdateListener task : tasks)
        {
            out.writeObject( task );
        }

  }

Synchronize keyword is not neccessary, method is called in synchronize block.

Upvotes: 1

Related Questions