Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java. Serialization of objects in a multithreaded environment

I have an object whose internal mutable state is being constantly updated by one or more threads. The object is synchronized, and the goal is to periodically save its state (via serialization) from yet another thread:

public class Counter implements Serializable {
    private int dogCount;
    private int catCount;

    public synchronized void updateFromDogThread( int count ) { 
        dogCount = count; 
    }

    public synchronized void updateFromCatThread( int count ) { 
        catCount = count; 
    }
}

Questions:

  • Is serialization safe in this case?
  • How does it work under the hood? That is to say, will the ObjectOutputStream performing the serialization block until no threads are any longer operating on Counter?
  • What if Counter's synchronization doesn't use the intrinsic lock, but some other lock?
like image 405
Jake Avatar asked Feb 27 '23 19:02

Jake


1 Answers

  • Is serialization safe in this case?

No. As @Tom Hawtin says, you will need to perform your own locking to ensure that the object(s) are not changed while you are serializing them.

  • How does it work under the hood? That is to say, will the ObjectOutputStream performing the serialization block until no threads are any longer operating on Counter?

ObjectOutputStream does no locking under the hood. It is up to the application to do this, if it is necessary.

  • What if Counter's synchronization doesn't use the intrinsic lock, but some other lock?

Then your application will also need to use that other lock to lock out updates while serialization is happening.

If the state that you are serializing simply consists of the state of one object with two fields, then lock contention and granularity should not be a problem. But if the object(s) are complicated, then lock contention could well be problematic, as could the problem of acquiring the locks without risking deadlock. That scenario would require careful design.

like image 141
Stephen C Avatar answered Mar 01 '23 11:03

Stephen C