Friday 9 August 2013

Top Most How to work with transient variable in java (an example tutorial)

Transient keyword in java is comparatively less common than any other keyword like volatile.since transient is less common it becomes even more important to understand correct usage of it. In One word transient keyword is used in serialization process to prevent any variable from being serialized, so if you have any field which is not making sense to serialize, you can simply declare that as transient and it won't be serialized.In this article we will revise some basics like
What is transient variable in java, why do we need transient variable and most importantly where should we use transient variable or which fields need to be declared as transient with example.

What is transient variable in Java?

transient variable, transient keyword javaIn simple sentence any variable which is modified with transient keyword becomes transient variable in java.But before understanding about transient variable let recap something about serialization in java. Serialization is a process by which object's state is saved by JVM and during deserializaiton it’s recovered by JVM. During Serialization all property of object gets saved except static and transient. So if we would like to exclude any property of an object from being serialized we mark it transient and then JVM doesn't serialize it. While marking any property transient its worth noting to provide it a default value during deserialization otherwise deserialized object is not properly usable.

Why do we need transient variable in java?

Transient keyword provides you some control over serialization process and gives you flexibility to exclude some of object properties from serialization process. Some time it does make sense not to serialize certain attributes of an object, we will see which variables should not be serialized and should be made transient in next section.

Which variable you should mark transient?

This is a good question; since we know the purpose of transient keyword or having transient variable its make sense to think about which variable should be marked as transient. My rule is that any variable whose value can be calculated from other variables doesn't require to be saved. For example if you have a field called "interest" whose value can be derived from other fields e.g. principle, rate, time etc then there is no need to serialize it.

Another example is of word count, if you are saving article then no need to save word count, because it can be created when article gets deserialized. Another good example of transient keyword is "Logger" since most of the time you have logger instance for logging in Java but you certainly don't want it to serialize correct?

Example of transient variable in java

To understand the concept of transient variables let see a live example in java.


public class Stock {
    private transient Logger logger = Logger.getLogger(Stock.class); //will not serialized
    private String symbol; //will be serialized
    private BigInteger price; //serialized
    private long quantity; //serialized
}

Important points about transient keyword in java

Here are few important points about transient variables in java which I found, let me know if you have some more which I missed out here and I will include here.

1) Transient keyword can only be applied to fields or member variable. Applying it to method or local variable is compilation error.

2) Another important point is that you can declare an variable static and transient at same time and java compiler doesn't complain but doing that doesn't make any sense because transient is to instruct "do not save this field" and static variables are not saved anyway during serialization.

3) In similar way you can apply transient and final keyword together to a variable compiler will not complain but you will face another problem of reinitializing a final variable during deserialization.

4) Transient variable in java is not persisted or saved when an object gets serialized.


That's all from me on transient keyword, let me know how do you use it and if you know any pecularity about transient keyword or something which we need to be aware while using it and missed out here. You can also refer’s Sun Glossary for meaning of different keywords in Java.


Related tutorials in Java


LinkWithin

Related Posts Plugin for WordPress, Blogger...

Labels

Core Java programming core java interview question Core Java Faq's Servlets coding database jsp-servlet spring Java linux unix interview questions java investment bank Web Services Interview investment bank mysql Senior java developer interviews best practices java collection tutorial RMI SQL Eclipse FIX protocol tutorial tibco J2EE groovy java questions SCJP grails java 5 tutorial jdbc beginner error and exception Design Patterns Java Programming Tutorials fundamentals general object oriented programming xml Java Programs Hibernate Examples Flex JAMon Java xml tutorial logging Jsp Struts 2.0 Sybase and SQL Server debugging java interviews performance FIX Protocol interview questions JUnit testing WebSphere date and time tutorial experienced java IO tutorial java concurrency thread Ejb Freshers Papers IT Management Java Exapmle Java Script SQL and database tutorial examples Scwcd ant tutorials concurrency example and tutorial future state homework java changes java threading tricky Agile Business of IT Development JSTL Java JSON tutorial Java multithreading Tutorials PM Scrum data structure and algorithm java puzzles java tips testing tips windows 8 5 way to create Singleton Object Architect Interview Questions and Answers Architecture Architecure Bluetooth server as swing application that searches bluetooth device in 10 meter circle and show all devices. You can send file to any bluetooth device. C Programming CIO Callable Statement in Java Circular dependency of Objects in Java Comparable Example in Collection Custom annotation in Java Developer Interview Divide and rule example in java Drupal Example of Singleton Pattern FIX protocol ForkJoin Example in Java 7 Get data from dynamic table with Java Script Git HTML and JavaScript Health Hello World TCP Client Server Networking Program Hibernate Basics Hibernate Interview Question Answer J2EE Interview Question And Answers J2ME GUI Program JEE Interview QA JMS interview question Java J2EE Hibernate Spring Struts Interview Question Java System Property Java Threads Manager Portlets Provident Fund Read data from any file in same location and give the required result. Reading Properties File in Java Redpoint Rest WebService Client Rest Webservice Test SAL join with ven diagram SCP UNIX COMMAND SSL Singleton Pattern in Java Spring Bean Initialization methods and their order Spring Interview Questions Struts Struts 2.0 Basics Struts 2.0 Design Pattern Submit Html Form With Java Script On The Fly Unix executable For Java Program XOM DOM SAX XP books computers core java; core java; object oriented programming data structure; java investment bank; design pattern dtd duplicate rows in table get browser name with jquery grails podcast inner class java beginners tutorial java cache java networking tutorial java spring java util; java collections; java questions java.java1.5 linked list mailto function with all browser oracle database oracle duplicate rows orm schema social spring mvc questions struts transaction tricks tweet windows xslt