How to get Transient Variable Original value after deserialization - java

With Transient variable we can stop serializing the required values, but after deserialization we are getting default values of transient variables and we are loosing the original values. So then what is the need of creating transient variable instead we can skip creating the variable itself. If possible how to get the original value of transient variable.

The idea of a transient variable is that there's no meaning to persist its original value in serialized form, since it wouldn't be in a valid state after de-serialization (think, for example, about a member variable that holds an open Socket).
After de-serialization of the object, the transient variable should be initialized by some method call (for example, the getter of that member may initialize it if it's null).

As for the explanation of Why is there a transient keyword? / What is the use of transient variables? I like to point to this question:
Why does Java have transient fields?
It neatly explains that transient variables are used for i.a. for performance reason, say pre-calculating certain values that come from the combination of other values stored in the object. You need them in your code, but they would only take up valuable space when the object is serialized and sent/stored somewhere.
Another use would be, as mentioned by Eran, to store variables in the object that are necessary for it's function but at the same time are for example dependent on the underlying system.
As for How to get the original value of the transient variable?, there is no clean way to do that afaik. Especially if you serialize and object for transfer between two applications there is no way as the data simply does not exist.

Consider very basic scenario Person class
class Person{
private Name
private DOB
private Age}
In this, storing the Name and DOB makes sense, but storing Age doesn't as it always change on a daily basis, so declare it as transient
and it can be always calculated as Current date - DOB, which will give the accurate Age.

First of all transient keyword is used along with instance variables to exclude them from serialization process. if a field is transient its value will not be persisted.
The perfect use of Transient variable can be seen in Hibernate.
For and example in you Database table there are only two column (name and surname)
but in your POJO entity you are having three variable (name , surname and age) in this situation you can make Transient to age field and you can save your entity without any complain as age variable becomes as transient not going to persist.

Related

What's the correct architectual pattern for storing object references in Java?

In a Java Application you many times face a situation, when you want to store all Object References for newly created objects, for example to retrieve it by a specific key later. Key can be any of this object's fields. There are many Collections, that are suitable for it:
List
Map
Set
etc...
All of them have one similar thing, if you want to use it, you have to put it inside a variable. Static variables are bad and should not be used, so variable also needs a class that will hold it. How should you name a class, that is responsible for storing references to other class's objects? Also, is it a good practice to put a method for retrieving a single reference from this "manager" class? Is there some way to automatically generate this kind of class, by its key?

Ormlite ignore field when calling createOrUpdate

Is there an annotation that I can apply to a field that when calling createOrUpdate and passing the object that the specific field will not be updated if the object already exists.
The use case is I have a creation date in my object (which is set to current time of Java object creation) but if the object already exists in the database I do not want the date to be updated but would want the other fields updated. Would it be better to do a query on the id (create if it doesn't exist) and then in my code just iterate through the other fields and do updates for any that are different.
Is there an annotation that I can apply to a field that when calling createOrUpdate and passing the object that the specific field will not be updated if the object already exists.
Hrm. No there isn't. One thing you could do is create a class which has the same fields but without the date field. Or you could have a base-class with all of the fields except the date field. Then have a sub-class which adds the date field. Both classes would save to the same table. You would save the one with the date object when you want to use it.
Hope this helps.
I did this by using readOnly attribute.
#DatabaseField(columnName = "last_value_date", readOnly = true)
private Date lastValueDate;
During the update, all readOnly attributes are skipped from update query.

Cache objects as Immutable classes

I am asking very generic question and the answer can vary from requirement to requirement, but for "general" or "rule of thumb", can we say the following is a good design rule:
The classes to be cached (static/reference data) should be designed as
immutable, with exceptions reasoned.
What could be design/performance issues with the above statement, if this is not true?
#JohnB has a good answer about the underlying data.
If, however, the question is referring to the immutability of the cached classes themselves (which are holding the data in the cache), then the answer is that mutable classes can cause thread-safety issues if the instances of the classes are referenced by multiple threads (as can often happen with data shared via a cache). Additionally, "accidental" modification of the data may occur, where a shared instance is unintentionally modified (because the modifying code did not know that the data was shared).
This is because of what a cache does, which is hold data rather than retrieving it from the data source again. For example, you query the database for a value then put it in a memory-based cache so you don't have to query the DB again. However, if the value in the DB can change then the value in the cache will be out of date and your application will be using the wrong data.
Therefore, caching is best if the data cannot change during the live of the application. If the data can change, then a strategy must be developed to regularly check to see if the data has changed.
What jtahlborn is explaining in other words : an immutable class will provide methods to obtain "static" data.
If your class is immutable, you will NOT have setters except the parameters in the constructor.
Take care making this : immutable classes are not made to be used only once, it would result in a performance loss, since copies of inner attributes have to be done each time you access the get... methods.
Example :
class MyImmutableThing {
private final String myProperty;
MyImmutableThing(String myProperty) {
this.myProperty = myProperty;
}
String obtainMyProperty() {
return myProperty;
}
// note there is no mean to modify the myProperty value : the original value remains ;)
// That's it !
}

Which variables or Objects should be associated with transient keyword?

I have read about Serialization theory part , where it says it is required when an object state need to be persisted .
I have written a Web Service Application , Where it will run on different JVMs
I am in the process of improving the performance of my Web Service so I have decided to use transient keyword for some of my Variables inside my Webservice class
I have some questions related to it as what object need to be serialized and what should not be
1.First to start with for my Logger , I will use the keyword transient
For example :
private transient static final Logger logger = Logger.getLogger(Tata.class);
2.But what about the instance variables inside the class ?? do we need to use transient for them or not ??
For example :
String strategyData = null;
String errorText = null;
Properties prop = null;
Please share your inputs .
if the variable is declared as transient, then it will not be persisted. It is the main purpose of the transient keyword.
so all those variables which you do not need to store in the persisted state of the object can be declared as transient.
refer http://www.javabeat.net/tips/168-what-is-transient-keyword-in-java.html for more details
You should mark as transient all fields that cannot or should not be serialized together with other object fields.
Field that is not serializable itself cannot be serialized and therefore must be marked as transient if it belongs to serializable class. The example is class that contains several fields and one of them is Thread. Obviously thread cannot be serialized. Therefore mark it as transient and implement mechanism that creates new thread when object is restored after serialization.
Other example is when field can be but should not be serialized. For example process ID. Assume that your program holds process ID of other process. The process ID itself is int, so there is not problem to serialze it. But it does not have any sense in other environment or in the same environment in several minutes (because that process probably already does not exist).
The web service class itself is never serialized. The data objects that are returned by the web service methods, as well as their arguments, are serialized. They should contain information needed by the recipient of the object.
If some information is not needed by the recipient, and if the object will not cause exceptions with this information set to null, then you can mark it as transient. But if it's not needed by the recipient, it should probably not be part of the object in the first place.
If you're using a logger inside the DTO, then this logger should definitely not be serialized. But make sure to check that the logger is not null each time you're using it, then.
What do you mean by 'run on different JVMs' ?
If it would run simultaneously on several JVMs (a distributed server for instance) than no the variables that represent the state of your object must not be transient.
Otherwise the other servers instances would get your service in an inconsistent state.
visit the link which might be useful to you..
http://javarevisited.blogspot.com/2011/09/transient-keyword-variable-in-java.html
Serialization is used incases where you need to persist state of your object. Or need to trasfer the object state between different machine (or virtual machine, if you are using more than one vm on a single machine) etc.
For ex. If you what the state of the object even after restarting the system, You can use serialization.
Also, You may not required to save all the state in the object. For that you can declare that variable as transient.
If you need only strategyData to be persisted, you can declare the other two variables as transient.
Note. If you need to serialization an object. All the object referred inside must also be Serializable, or you need to declare them as transient.

java gson - is it possible to deserialize an object from a string without having all of its fields

Lets say I am adding a field to the object and I still get the same string . Can I de-Json it into an object with the missing fields set as null?
what if I have primitive variables there ?
10x
Well, depends on how the deserialization is done. If the object is first created with a no-arg constructor and then the fields are set via setters or reflection, I'd say this should work. In that case, every reference to other objects would be null whereas primitive types get their default values (for numbers 0, for boolean false, etc.)
Yes
Gson - Finer Points with Objects
While deserialization, a missing entry in JSON results in setting the corresponding field in the object to null
You can use XStream to (de)serialize to JSON, and this is how they deal with new fields: http://x-stream.github.io/faq.html#Serialization_newer_class_versions
So the short answer is: references will be null references, primitives will keep the values they got in constructor

Categories