can volatile variable be serialized in java - java

Transient and static variable can not Serialize
According to Joshua Bloch’s excellent book “Effective Java Programming Language Guide”, “ the volatile modifier guarantees that any thread that reads a field will see the most recently written value "
but what about volatile be serialized or not.

A volatile is typically serialized by Java Object Serialization. The threading / JMM properties of volatile are orthogonal to serialization.
Incidentally, it is possible to serialize a transient or static variable, if you code custom writeObject / readObject methods to do this. But, this isn't done by the default serializer.
You wouldn't expect a transient variable to be serialized. After all transient is essentially a hint to not include the field in a serialization.
The reason that static variables are not included in an object serializations (by default) is that statics don't "belong" to a specific object.

Yes, it can be serialized. The field modifier volatile is used for the Java Memory Model to ensure that all Threads see a consistent value. It does not restrict its persistence.

Related

Do all variables in a serialized class become part of the serialization process in Java?

[enter image description here][1]
[1]: https://i.stack.imgur.com/Bk99T.pngstrong text
In addition, does it matter whether the variables being part of the serialization process are instance variables or variables in conductors in methods or object variables?
Serialization with the marker interface you mentioned is a tough topic in Java. All member fields of an object will get serialized, except the ones marked with the keyword transient. Other variables like local variables or parameters to constructors or methods are not serialized.
It is easy to corrupt a Java program by deserializing malicious or corrupted data. You can customize, what will be serialized by implementing the methods private void readObject(ObjectInputStream s) and private void writeObject(ObjectOutputStream s)
As you can see, those private (!) methods are not members of the interface Serializable, so it's compiler magic that calls them for serialization. If you do not implement them, there is a default implementation.
Don't forget to specify the variable
private static final long serialVersionUID = 1L; and give it a new value for each update of your member fields - this will prevent that you deserialize data from another version of your class where the data does not suite the implementation.
In general: If you really have to use serialization, I would recommend that you read more articles on it, e.g. https://ahdak.github.io/blog/effective-java-part-11/ - it summarizes from the book "Effective Java" by Josh Bloch.
Also the Java Object Serialization Specification could be interesting for you.

Java non-persistent but serializable variable

In java, how can I declare a variable which is not persistent to a database but it is serializable so that the variable is present in JSON representation of the object containing the variable?
I used the annotation #javax.persistence.Transient, but it doesn't work the way I want since #Transient variables are not serializable.
The issue may be solved by a specific workaround using modifiers. In order to avoid persisting fields, you have 4 options: marking the field with the modifier static, final or transient; or adding the #Transient annotation. Each of these will prevent the field from being persisted into the DB (see here).
Not all these limitations also apply to serialization though. Static and transient modifiers will prevent serialization, but final modifier will not - it will not be persisted but will be serialized (Deserializing in this case is a bit longer, but possible).
I hope this will be applicable to your issue.

Does volatile propagate to instance members?

Suppose there is some simple container declared and instantiated like this
class Test {
private volatile List<Object> list = new ArrayList<>();
}
, and reads and writes to it are guarded by locks; synchronized keyword not used. Although Test.list is declared volatile, none of its member fields like ArrayList.elementData also bear this modifier. Now, in multithreaded application, will it behave like volatile container? In other words, will changes submitted to ArrayList.elementData by some thread be visible immediately by all other threads?
The general answer is no: volatile only establishes a happens-before relationship between reads and writes to the reference variable. If two threads concurrently access an inner field of the object referenced in the variable, there still needs to be a synchronization mechanism.
In your case, the best approach seems to use a synchronized list, or some wrapper from the java.util.concurrent package.
Short answer: no. As a consequence, array elements are always non-volatile (even if the array itself is declared volatile). You need to use special concurrent-friendly implementation of the List. Usually java.util.concurrent.CopyOnWriteArrayList fits the needs. If you assign the list variable only once, then volatile keyword does not change anything (in this case better to use final).

Are class variables in Java shared between threads or not?

I was wondering when declaring a class variable (i.e. a variable declared outside a method) would potentially cause problems in a program that's executed by several threads. I suppose finals are save to use (i.e. not shared), and static variables are definitely shared between threads. But what about "standard" variables? When are they shared and when are they "private" to each individual thread?
Update: While I accept that local variables (within methods) are not shared and class variables usually are I would love to understand why that is (from a technical point of view). So any explanation to that effect (or links to articles that are fairly easy to understand) would be much appreciated.
Java provides the ThreadLocal<T> class to declare variables that are not shared between threads. Non-final parameters and local variables are also not shared between threads. final parameters and locals variables may be shared between threads when they are used in an anonymous class definition, but this shouldn't be a problem since they are final. In all other cases I can think of, variables can be shared between threads.
The short answer is, any method or variable, both static and non-static, has the potential to be accessed by more than one Thread if its access modifier makes it visible to that Thread.
The concept of "thread-safe" is entirely different. If a variable is read-only (final can be used to make primitives read-only, but only makes references to objects immutable, not the objects themselves), multi-threaded access of that variable is inherently thread-safe. If it can be written to, the proper use of synchronized blocks or the volatile keyword is necessary to ensure mutual exclusion.
There's nothing special about a standard variable that shields it from multi-threaded access and resulting problems. That's up to YOU the programmer to worry about.
If two threads need to safely access the same instance fields, then YOU have to write code to manage that.
Some common techniques are to use synchronized blocks to manage mutability, using atomic or final primitives (a final Object is not necessarily safe unless you know the Object isn't mutable), or simply use a ThreadLocal to give each thread its own unshared instance of the class.
Final doesn't mean 'not shared' just that the field cannot be overwritten, it can only be initialized one.
Static behavior is also not related to threading, static means that the field has a Class scope and not instance scope, meaning it's shared by all the instances of a Class.
If you want to protect a field from being modified by many threads, you have to manipulate it through synchronized methods.
Such variables are called the fields of the class, and they are definitely not "thread-safe" in general, even when they are final (because final only refers to the reference itself, not what's inside the object).

which is the apt java keyword to skip java serialization

In a process of leaning java serialization concept, i was puzzled at one point. In java serialization process, we use 2 keywords to prevent serialization, i.e.., transient and static. If i don't want to save an instance variable, which keyword should i use, both does exactly the same.
Class A implements Serializable{
private static int x;
private transient int y;
private transient static int x;
}
In the above code all the three instance variables are not saved in a process of serialization. Which keyword is apt and recommended to prevent serialization. Why does two keywords have almost the same functionality. What is the recommended way of declaration to prevent serialization. Correct me if I'm wrong, I'm still learning.
The static keyword transforms an instance variable into a static variable. A side-effect is that the field is not serialized anymore... because it's not a field anymore.
A static variable is a variable of the class. An instance variable is a variable of the object, or instance of the class. You can't blindly go from one to the other.
Read the tutorial page about instance and static variables.
The transient keyword is the right keyword to use, of course.
You are confused: static fields are not instance variables, they are class-wide variables. By declaring a field static, the same field is shared among all instances of this class - it is not part of any specific object anymore, which leads to it not being serialized.
To specifically prevent serialization only transient is applicable...
Transient (and in JAXB XmlTransient) signify that the data is ephemeral and not of permanent importance and thus should just be ignored when it comes to matters of persistence.
Static means the value applies that the class level and thus serializing/deserializing it for multiple instances would be unsafe as values would collide.
Well, Let me define serialization once more.
A serialization is a process in which we persist state of an object.
So, is any static variable is part of an object's state ?..No absolutely not. It is the data which is shared among all objects of a class. So obviously, any static variable is not supposed to be serialized with object's state.
let's assume, we are allowed to persist an object's state. later on, if this variable is changed by some other object/class itself, and if we try to de-serialize the object then what value this static variable will hold. There will be a clash.
So if you want to prevent any instance variable from being serialized , do use transient.
when you will de-serialize the object it will be initialized with a default value.

Categories

Resources