Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why Locks are Serializable in java?

One question arised in my mind while looking into the implementation of the ReentrantLock class. ReentrantLock is serializable and in the documentation it says that any deserialized lock is always unlocked irrespective of the state when it was serialized. This make sense because the state Lock and unlock is basically based on the threads at the runtime (who hold the lock) and while we de-serialize those threads may not be available.

Question is : Why we need the Lock to persist because it does not store it’s basic state (locked/unlocked) ? Right now I can assume that may be for the fairness property of the lock. But fairness is again depending on the underlying OS so if we persists the lock on one platform and deserialized on another because (write once and run anywhere) it may not work so no point in persisting only for fairness.

Hope I clearly put my confusion about Lock serialization in java.

like image 892
Gourabp Avatar asked Jul 31 '13 19:07

Gourabp


People also ask

What is serializable in locking?

SERIALIZABLE is the strictest SQL transaction isolation level. While this isolation level permits transactions to run concurrently, it creates the effect that transactions are running in serial order. Transactions acquire locks for read and write operations.

Why do we need serializable in Java?

Serialization in Java allows us to convert an Object to stream that we can send over the network or save it as file or store in DB for later usage. Deserialization is the process of converting Object stream to actual Java Object to be used in our program.

Why do we need to serialize objects?

Serialization is the process of converting an object into a stream of bytes to store the object or transmit it to memory, a database, or a file. Its main purpose is to save the state of an object in order to be able to recreate it when needed.

What is the purpose of serializable interface?

Serializable is a marker interface (has no data member and method). It is used to "mark" Java classes so that the objects of these classes may get a certain capability. The Cloneable and Remote are also marker interfaces. The Serializable interface must be implemented by the class whose object needs to be persisted.


1 Answers

http://docs.oracle.com/javase/7/docs/api/java/util/concurrent/locks/Condition.html http://download.java.net/jdk7/archive/b123/docs/api/java/util/concurrent/locks/ReentrantLock.html

I would say that the reason why Lock persists is so that you're able to serialize objects that depend on Lock itself. If Lock wasn't serializable, anything dependent on it wouldn't be able to be serialized either.

You'd also be able to store the owner, holdCount, queuedThreads and all of the other stuff that you can see on the API page that I linked above for ReentrantLock.

like image 199
Ricky Mutschlechner Avatar answered Sep 22 '22 12:09

Ricky Mutschlechner