Labels

.NET Job Questions About Java Absract class Abstract class Abstract Class and Interface Aggregation ajax aop apache ofbiz Apache ofbiz tutrial Association authentication autocad basics batch Binary Tree bootstrap loader in java build Builder design pattern C++ Job Questions caching CallableStatement in java certifications Chain of responsibility Design pattern charts check parentheses in a string Classes classloader in java classloading concept code quality collage level java program Composition concurrency Concurrency Tutorial Converting InputStream to String Core Java core java concept core java interview questions Core Java Interview Questions Core Java Questions core java tutorial CyclicBarrier in Java data structures database Database Job Questions datetime in c# DB Db2 SQL Replication deserialization in java Design Patterns designpatterns Downloads dtd Eclipse ejb example/sample code exception handling in core java file handling injava File I/O vs Memory-Mapped Filter first program in spring flex Garbage Collection Generics concept in java grails groovy and grails Guice Heap hibernate Hibernate Interview Questions how-to IBM DB2 IBM DB2 Tutorial ide immutable Interceptor Interface interview Interview Questions for Advanced JAVA investment bank j2ee java JAVA Code Examples Java 7 java changes java class loading JAVA Classes and Objects Java Classloader concept Java classloading concept java cloning concept java collection Java collection interview questions Java Collections java concurrency Java CountDownLatch java definiton Java design pattern Java EE 5 Java EE 6 Java Exceptions Java file Java Garbage Collection Java generics Java Glossary java hot concept java immutable concept Java Interface Java interview Question java interview question 2012 java interview question answer Java Interview Questions Java Interview Questions and Answers java interview topic java investment bank Java Job Questions java multithreading java multithreading concept java new features Java Packages java proxy object java questions Java Serialization Java serialization concept java serialization interview question java session concept java string Java Swings Questions java synchronization java threading Java Threads Questions java tutorial java util; java collections; java questions java volatile java volatile interview question Java Wrapper Classes java.java1.5 java.lang.ClassCastException JavaNotes javascript JAX-WS jdbc JDBC JDBC Database connection jdk 1.5 features JDK 1.5 new features Concurrent HashMap JMS interview question JMS tutorial job JSESSIONID concept JSESSIONID interview Question JSF jsp JSP Interview Question JSP taglib JSTL with JSP Junit Junit Concept Junit interview question.Best Practices to write JUnit test cases in Java JVM Linux - Unix tutorial Marker Interfaces MD5 encryption and decryption messaging MNC software java interview question musix NCR java interview question Networking Job Questions news Object Serialization Objects ojdbc14.jar OOP Oracle Oracle SQL Query for two timestamp difference orm own JavaScript function call in Apache ofbiz Packages Palm Apps patterns pdf persistence Portal Portlet Spring Integration Prime number test in java programs Rails Reboot remote computers REST Ruby Sample application schema SCJP security Senior java developer interviews servlet3 servlets session tracking singleton design pattern Spring Spring 2.5 Framework spring ebook Spring framework concept spring MVC spring pdf Spring Security Spring Security interview questions SQL SQL performance SQL Query to create xml file Sql Query tuning ssis and ssrs StAX and XML string concept string immutable string in java strings struts Struts2 Struts2 integration synchronization works in java Technical Interview testing tips Tomcat top Tutorial Volatile in deep Volatile working concept web Web Developer Job Questions web services weblogic Weblogic Application Server websphere what is JSESSIONID xml XML parsing in java XML with Java xslt


Saturday, 13 July 2013

Volatile & Transient

volatile
The volatile keyword is used on variables that may be modified simultaneously by other threads. This warns the compiler to fetch them fresh each time, rather than caching them in registers. This also inhibits certain optimisations that assume no other thread will change the values unexpectedly. Since other threads cannot see local variables, there is never any need to mark local variables volatile.

transient
Transient instance fields are neither saved nor restored by the standard serialisation mechanism. You have to handle restoring them yourself.· The volatile keyword

It warns the compiler that other Threads may change an instance or class variable at any time, and that the compiler should not cache that value in a register, least it be stale. Volatile does not imply any locking. It simply that the compiler/JVM does not cache volatile values in registers. On every use, it fetches the value from main shared RAM. On every assignment it saves the value to main shared RAM. In a multicpu machine with cache coherency, the value may not actually be stored all the way back to RAM, but logically it is. Declaring a long or double volatile also ensures it is fetched and stored atomically in one indivisible 64 bit chunk, rather than two 32 bit chunks one after the other as is normal. Volatile is insufficient to ensure even code as simple as x++ works. Pathologically you could see this happening: Thread (a) reads x, thread (a) increments x in a register, thread (b) reads x, thread (b) increments x in a register, thread (b) saves x, thread (a) saves x. The result is only one increment instead of two. You may think this highly improbable, but in the nanoscopic world of the CPU billions of events happen every second, so that highly "improbable" things happen frequently, or, even more infuriatingly, only during demos.


public class TestSerialization {
   // ***********************************************************************************
   public static void main(String[] args) throws Exception {
      TestSerialization ts = new TestSerialization();
      ts.testInstanceObjest();
      ts.testClassObjest();
   }
   // ***********************************************************************************
   void testInstanceObjest() throws Exception{
      // Serialize output an Instance Object
      ObjectOutputStream out = new ObjectOutputStream(new FileOutputStream("t1.tmp"));
      out.writeObject(new MySerializabe());
      out.flush();
                  
      // ATTENTION: Changed the static and transient static value after storage
      MySerializabe.si  = 10000;
      MySerializabe.tsi = 100000;
      // Read back Serialized Instance Object
      ObjectInputStream in = new ObjectInputStream(new FileInputStream("t1.tmp"));
      MySerializabe mys = (MySerializabe)in.readObject();
      in.close();
      // .............................................................
      // Show the results
      System.out.println("Output from testInstanceObjest():\n");
      // instant values are serialized
      System.out.println("instance variable str          : " + mys.str);
      System.out.println("instance variable i            : " + mys.i);
      // static values are not serialized for an instant object!
      // The new value is picked up, not the old ones!
      System.out.println("static variable sstr           : " + mys.sstr);
      System.out.println("static variable si             : " + mys.si);
      // transient values are not serialized
      System.out.println("transient variable tstr        : " + mys.tstr);
      System.out.println("transient variable ti          : " + mys.ti);
      // transient static values are not serialized 
      // The new value is picked up, not the old ones!
      System.out.println("transient static variable tsstr: " + mys.tsstr);
      System.out.println("transient static variable tsi  : " + mys.tsi);
   }
   // ***********************************************************************************
   void testClassObjest() throws Exception {
      // Serialize output Class Object
      Class c = Class.forName("MySerializabe");
      ObjectOutputStream out = new ObjectOutputStream(new FileOutputStream("t2.tmp"));
      out.writeObject(c);
      out.flush();
      // ATTENTION: Changed the static and transient static value after storage
      MySerializabe.si  = 11111;
      MySerializabe.tsi = 111111;
      // Read back Serialized Class Object
      ObjectInputStream in = new ObjectInputStream(new FileInputStream("t2.tmp"));
      Class cls = (Class)in.readObject();
      in.close();
                  
      // .............................................................
      // Show the results
      System.out.println("\nOutput from testClassObjest():\n");
 
      // Only field with static modifier is legal to get value back
      // The new value is picked up, not the old ones!
      // which means they are both not serialized.
      // The conclusion: static and tansient static does not make any differece
      System.out.println("static variable sstr           : " + cls.getDeclaredField("sstr").get(cls));
      System.out.println("static variable si             : " + cls.getDeclaredField("si").getInt(cls));
      System.out.println("transient static variable tsstr: " + cls.getDeclaredField("tsstr").get(cls));
      System.out.println("transient static variable tsi  : " + cls.getDeclaredField("tsi").getInt(cls));
      // all other fields will cause exceptions
      // uncomment this code and try it out!
      // System.out.println(cls.getDeclaredField("i").get(cls));
      // .............................................................
      // Obviously the serialzed Class object know all fields in itself
      System.out.println("\n  Print some reflections from Class MySerializabe:");
      System.out.println("     " + cls);
      System.out.println("     " + cls.getDeclaredField("str"));
      System.out.println("     " + cls.getDeclaredField("tstr"));
      System.out.println("     " + cls.getDeclaredField("sstr"));
      System.out.println("     " + cls.getDeclaredField("tsstr"));
      System.out.println("     " + cls.getDeclaredFields());
   }
}
// ***********************************************************************************
class MySerializabe implements Serializable {
                    String str   = "STRING";
             static String sstr  = "STATIC STRING";
   transient        String tstr  = "TRANSIENT STRING";
   transient static String tsstr = "TRANSIENT STATIC STRING";
      
                    int i   = 1;
             static int si  = 10;
   transient        int ti  = 100;
   transient static int tsi = 1000;
}

/* OUTPUT:
Output from testInstanceObjest():
instance variable str          : STRING
instance variable i            : 1
static variable sstr           : STATIC STRING
static variable si             : 10000
transient variable tstr        : null
transient variable ti          : 0
transient static variable tsstr: TRANSIENT STATIC STRING
transient static variable tsi  : 100000
 
Output from testClassObjest():
static variable sstr           : STATIC STRING
static variable si             : 11111
transient static variable tsstr: TRANSIENT STATIC STRING
transient static variable tsi  : 111111
 
  Print some reflections from Class MySerializabe:
     class MySerializabe
     java.lang.String MySerializabe.str
     transient java.lang.String MySerializabe.tstr
     static java.lang.String MySerializabe.sstr
     static transient java.lang.String MySerializabe.tsstr
     [Ljava.lang.reflect.Field;@64f64241
*/

No comments:

Post a Comment

LinkWithin

Related Posts Plugin for WordPress, Blogger...