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 onCounter
? - What if
Counter
's synchronization doesn't use the intrinsic lock, but some other lock?