Use of volatile modifier

can any one explain me the use of volatile modifier

What does volatile do?
This is probably best explained by comparing the effects that volatile and synchronized have on a method. volatile is a field modifier, while synchronized modifies code blocks and methods. So we can specify three variations of a simple accessors using those two keywords:
int i1; int geti1() {return i1;}
volatile int i2; int geti2() {return i2;}
int i3; synchronized int geti3() {return i3;}
geti1() accesses the value currently stored in i1 in the current thread. Threads can have local copies of variables, and the data does not have to be the same as the data held in other threads. In particular, another thread may have updated i1 in it's thread, but the value in the current thread could be different from that updated value. In fact Java has the idea of a "main" memory, and this is the memory that holds the current "correct" value for variables. Threads can have their own copy of data for variables, and the thread copy can be different from the "main" memory. So in fact, it is possible for the "main" memory to have a value of 1 for i1, for thread1 to have a value of 2 for i1 and for thread2 to have a value of 3 for i1 if thread1 and thread2 have both updated i1 but those updated value has not yet been propagated to "main" memory or other threads.
On the other hand, geti2() effectively accesses the value of i2 from "main" memory. A volatile variable is not allowed to have a local copy of a variable that is different from the value currently held in "main" memory. Effectively, a variable declared volatile must have it's data synchronized across all threads, so that whenever you access or update the variable in any thread, all other threads immediately see the same value. Of course, it is likely that volatile variables have a higher access and update overhead than "plain" variables, since the reason threads can have their own copy of data is for better efficiency.
Well if volatile already synchronizes data across threads, what is synchronized for? Well there are two differences. Firstly synchronized obtains and releases locks on monitors which can force only one thread at a time to execute a code block, if both threads use the same monitor (effectively the same object lock). That's the fairly well known aspect to synchronized. But synchronized also synchronizes memory. In fact synchronized synchronizes the whole of thread memory with "main" memory. So executing geti3() does the following:
1. The thread acquires the lock on the monitor for object this (assuming the monitor is unlocked, otherwise the thread waits until the monitor is unlocked).
2. The thread memory flushes all its variables, i.e. it has all of its variables effectively read from "main" memory (JVMs can use dirty sets to optimize this so that only "dirty" variables are flushed, but conceptually this is the same. See section 17.9 of the Java language specification).
3. The code block is executed (in this case setting the return value to the current value of i3, which may have just been reset from "main" memory).
4. (Any changes to variables would normally now be written out to "main" memory, but for geti3() we have no changes.)
5. The thread releases the lock on the monitor for object this.
So where volatile only synchronizes the value of one variable between thread memory and "main" memory, synchronized synchronizes the value of all variables between thread memory and "main" memory, and locks and releases a monitor to boot. Clearly synchronized is likely to have more overhead than volatile.
I got the above information from the below link......
http://www.javaperformancetuning.com/news/qotm030.shtml
and also we can describe the volatile modifier as
Volatile� A volatile modifier is mainly used in multiple threads. Java allows threads can keep private working copies of the shared variables(caches).These working copies need be updated with the master copies in the main memory.
But possible of data get messed up. To avoid this data corruption use volatile modifier or synchronized .volatile means everything done in the main memory only not in the private working copies (caches).( Volatile primitives cannot be cached ).
So volatile guarantees that any thread will read most recently written value.Because they all in the main memory not in the cache�Also volatile fields can be slower than non volatile.Because they are in main memory not in the cache.But volatile is useful to avoid concurrency problem.
This above information i got from
http://cephas.net/blog/2003/02/17/using-the-volatile-keyword-in-java/
Thats all i think you understood what a volatile modifier is.And if you got any doubts still in Java you can reach me to [email protected]
With Regards,
M.Sudheer.

Similar Messages

  • Use of volatile modifier in Serialization

    can any body explain me the use of this modifier in Serialization

    Volatile does not effect serialization.
    "transient" means the field is not serialized.

  • Need to report on sales order lines using specific pricing modifier

    Is there a report I can run for a specific modifier number that will give me all the sales order lines that were adjusted using that pricing modifier?

    Use oe_price_adjustments table and link that to the qp_list_headers and lines to get the details of the modifiers.
    Thanks
    Nagamohan

  • What is the use of account modifier in automatic account

    hi
    can someone explain the use of account modifier in automatic account

    The Account Modifier is used to break account determination down by movement type.
    For example, by default in SAP, the system says for movement type 101 and posting key PRD there is no modification. However, I can enter a code (e.g. XXX) against movement type 101 and posting key PRD and code YYY against movement type 102 and PRD.
    Then in u2018Configure Automatic Postingsu2019 when we go into posting key PRD, we will make entries for u2018general modifieru2019 XXX, account 400001 and YYY of 400002 (there will also need to be an entry for a u201Cblanku201D modifier which should cover all the other movement types).
    Regards,
    Chandra

  • How do I make use of Table Modifiers?

    Hi Experts
    I would like to use Table Modifiers in a web-report, but I have no idea about how to do it.
    I want to use table modifier since I am trying to do calculations based on cumulated values, which is not possible (since these are displayed values). Therefore I would like to ignore the number that appears in column 3 below and calculated by using a table modifier instead (let's say column a*b).
    (A and B are cumulated values)
    A | B | C
    1 | 3 | 3 (1 * 3)       -> 3 (when table modifier is used)
    3 | 4 | 2 (3-1 * 4-3) -> 12(when table modifier is used)
    5 | 6 | 4 (5-3 * 6-4) -> 30(when table modifier is used)
    Therefore could anyone please tell me the steps that I have to fullfill to make this change? I assume that I have to go to the Web Application Designer and edit the code?
    I'm using BW 3.5
    Thanks in advance, kind regards
    Torben

    I did find a "how-to"-guide

  • What is the use of Volatile Key word ??

    what is the use of Volatile Key word ??
    There is a primitive variable
    volatile int b = 10; // this is a master copy
    Locally thread A changes this int b as 5.
    Locally thread B changes this int b as 20.
    thread c want to use this int b.
    now what c will get??
    If didn't use volatile what will happen.
    Regards
    Dhinesh

    Deenu wrote:
    what is the use of Volatile Key word ??Why don't you ever reply to any of your threads? You never thank anyone for helping you, and this makes you one of the worst trolls out there.

  • Use of volatile

    public class MyClass {
         public static void main(String[] a) throws InterruptedException {
              new Thread(new A(),"thread1 ").start();
              Thread.sleep(500);
              new Thread(new A(),"thread2 ").start();
    class A implements Runnable {
         volatile int value = 0;
         public void run() {
              value++;
              System.out.println(Thread.currentThread().getName() + value);
    }Hi, I tried running this code with value being both volatile and not, but I get the same answer each time. Both threads turn value to 1. Shouldn't volatile make it 1 then 2?
    I tried the same thing but making value static, in which case it works as I thought it would have worked with volatile. I'm not too sure what volatile does anymore, could somebody please help clarify all this for me?
    Thanks.

    public class MyClass implements Runnable {
         Other o = new Other();
         public static void main(String[] a) throws InterruptedException {
              MyClass m = new MyClass();
              new Thread(m,"thread1 ").start();
              Thread.sleep(500);
              new Thread(m,"thread2 ").start();
         public void run() {
              o.value++;
              System.out.println(Thread.currentThread().getName() + o.value);
    class Other {
         volatile int value;
    }I looked at this one a bit longer, and I came up with this new example. Is this case more likely to need the volatile keyword as a precaution (as the variable in question is in an indepedent class)?
    Any help on this topic would be really appreciated. I looked up several websites on volatile, but none really clarified the use of volatile (actually, I don't recall whether any mentioned that the caching problem doesn't always happen!).
    Thanks.

  • I usually use PP at work.  can i use keynote to modify PP, then turn around and utilize Keynote new file in PP

    can i use keynote to modify PP, then turn around and utilize Keynote new file in PP?

    *Apple's stated System Requirements:*
    Mac computer with an Intel, PowerPC G5, or PowerPC G4 (500MHz or faster) processor
    512MB of RAM; 1GB recommended
    Approximately 1.2GB of available disk space
    32MB of video memory
    Mac OS X v10.4.11 or Mac OS X 10.5.6 or later
    QuickTime 7.5.5 or later
    The NVIDIA GeForce4 MX has a stated max 64mb of memory, but I could not see whether that meant it actually had that quantity. I would assume though that it had a minimum of 32mb.
    Have you checked in *About This Mac* what the actual memory is?
    Maybe Apple was optimistic in its minimum requirements.

  • Use of lr_core- modify

    Hi All,
    I have to modify these two field values.
    lv_inv_std_addr_flag
    lv_std_addr_flag
    DATA: lv_inv_std_addr_flag TYPE string,
              lv_std_addr_flag   TYPE string,
              lr_core            TYPE REF TO cl_crm_bol_core.
    Is it required to use the  lr_core->modify( ) statement twice to modify both the values as below
    lr_my_context->shipto->set_stdbpaddress( attribute_path = '' value = lv_inv_std_addr_flag ).
      lr_core->modify( ).
      lr_my_context->shipto->set_stdbpaddress( attribute_path = '' value = lv_std_addr_flag ).
      lr_core->modify( ).
    Or even the below code also works, beacuse it will be more effective in performance, as we are using lr_core->modify only once.
    lr_my_context->shipto->set_stdbpaddress( attribute_path = '' value = lv_inv_std_addr_flag ).
    lr_my_context->shipto->set_stdbpaddress( attribute_path = '' value = lv_std_addr_flag ).
    lr_core->modify( ).
    Edited by: Garg on Jun 17, 2009 4:44 PM

    as per my knowledge..one statment of modify after all statements works fine

  • How do I use Finder to modify file details in multiple files

    I am new to the mac (OS10.7.4) having recently transitioned from Windows (and go way back to CPM - for those that remember).  I am trying to achieve through finder what I can do in windows explorer by selecting multiple files, selecting  properties and then selecting (and then modifying) details.  I tried the similar thing on Finder using Get Info instead of Properties but only ended up with multiple windows, one for each file selected (and had to close each one individually! ).  Tried 'option-command-I' on multiple selected files, it worked, but the common tags that I wanted to alter where not available for editing.  I can simply, but clumsily, achieve the outcome I want by cutting and pasting the files to a usb stick, making the modifications on the windows machine and pasting them back on the mac.     This should be a simple basic operating system function regardless of platform - advice on how to find/achieve it appreciated!

    I find it best to use small little apps to help modify many files. Just serach for what you want to change and more often then not, you find software that does what you need, often free too.
    For Music tags: check out the free program "TriTag" to do what you want:
    http://www.feedface.com/projects/tritag.html
    For Music conversion (say, from FLAC to Apple Lossless) or MP3 to whatever... Use "XLD" (free)
    http://download.cnet.com/X-Lossless-Decoder/3000-2140_4-189505.html
    Bonus: VLC (free download) - has the ability to convert wma audio files, which is amazing, it's rare to find mac software that will convert wma to mp3 - http://9thport.net/2010/07/28/using-os-x-to-convert-wma-to-mp3-for-free/
    For file renaming in batch, I use "Name Mangler" - 10 bucks, app store.
    It has a lot of pro features and is very useful.
    good luck.
    - James

  • An error when I use InfoView to modify scheduled instances

    Is anyone familiar with this error:
    An error has occurred: Object reference not set to an instance of an object
    In the past if I wanted to make a change to an instance of a report; i.e. change the when, database logon, filters, destination, format, etc. I could use the InfoView, click history, then click reschedule of a report that was in a recurring status, make my changes and schedule it or could modify a report that has already ran.
    Now, if I try to modify scheduling detais through the InfoView I get the error:
    An error has occurred: Object reference not set to an instance of an object
    I now use the Central Management Console to alter distros, which is a hassle at times.
    The weird thing is I could use the InfoView one day, the next I couldnu2019t.
    Any ideas would be greatly appreciated.
    Thanks-

    Hi Vancoug,
    This problem can occur if an earlier version of Crystal Reports is installed on top of BusinessObjects Enterprise XI Release 2. To verify that this is the cause, run modules.exe and view the version of the DLLs that are loaded by IIS (w3wp.exe). To work properly, version 11.5.x should be loaded. Any previous versions of DLLs will cause this issue.
    then the solution would be: Perform a complete uninstallation of Crystal Reports and BusinessObjects Enterprise XI Release 2. Reinstall only XI Release 2 on this machine to restore the .NET InfoView functionality.
    Think this would be helpful..
    Thanks,
    Naveen.

  • ABAP pgm using append, sum, modify

    I am new to ABAP programming. Can somebody please help me out with the following program or give me some hints as to how to proceed?
    1. ABAP inputs: The pgm will have following parameters:
       P_ITEM - input string of 20 characters (select options)
       P_QTY - input number (select options)
       P_RATE - input number with 2 decimal points (select options) 
    2. Main processing logic:
       1. Accept 5 items each with qty and rate.
       2. store in internal table.
       3. calculate their price.
       4. sort on price in ascending order.
       5. display o/p as per section 3.
    3. Output format:
       ITEM     QTY     RATE     PRICE
       TOTAL
    Hints: For this ABAP make use of APPEND, SUM, MODIFY
    Thank you.

    This can be coded, but it does make much sense.  There is no "tie" between the selection-screen fields.  If you are assuming that the first value in P_ITEM corresponds to the first value in P_QTY and P_RATE, then you can do it, but this is not really a good way of coding.  Here is a sample anyway. 
    Add values to all three select-options and hit execute.
    report zrich_0004
           no standard page heading.
    data: begin of itab occurs 0,
          item(20) type c,
          qty type i,
          rate type p decimals 2,
          price type p decimals 2,
          end of itab.
    select-options: s_item for itab-item,
                    s_qty  for itab-qty,
                    s_rate for itab-rate.
    start-of-selection.
      clear itab. refresh itab.
      loop at s_item.
        clear itab.
        itab-item = s_item-low.
        read table s_qty index sy-tabix.
        if sy-subrc = 0.
          itab-qty = s_qty-low.
        endif.
        read table s_rate index sy-tabix.
        if sy-subrc = 0.
          itab-rate = s_rate-low.
        endif.
        itab-price = itab-qty * itab-rate.
        append itab.
      endloop.
      sort itab ascending by price.
      loop at itab.
        write:/ itab-item, itab-qty, itab-rate, itab-price.
      endloop.
    Welcome to SDN!  Please remember to award points for helpful answers and mark your posts as solved when solved completely.
    Regards,
    Rich Heilman

  • Use of volatile for variable in jdk 1.6 on Linux platforms

    Hello,
    I run the following code on my computer (dual core). This code just create two threads: one adds one to a value contained in
    an object and the other subbs one to it :
    // File: MultiCore.java
    // Synopsis: At the end of some executions the value of a is not equal
    // to 0 (at laest for one of teh threads) even if we do the
    // same number of ++ and --
    // Java Context: java version "1.6.0_11"
    // Java(TM) SE Runtime Environment (build 1.6.0_11-b03)
    // Java HotSpot(TM) Server VM (build 11.0-b16, mixed mode)
    // Linux Context: Linux 2.6.27-12-generic i686 GNU/Linux
    // Author: L. Philippe
    // Date: 03/10/09
    class MaData {
    public int a;
    public MaData() { a = 0; }
    public synchronized void setA( int val ) { a = val; }
    public synchronized int getA() { return a; }
    class MonThread extends Thread {
    MaData md;
    int nb, nb_iter;
    public MonThread( MaData ref, int rnb )
         md = ref;
         nb = rnb;
         nb_iter = 1000;
    public void run()
         if ( nb == 0 ) {
         for ( int i = 0 ; i < nb_iter ; i++ ) {
              // Increment MaData
              md.setA( md.getA()+1 );
         } else {
         for ( int i = 0 ; i < nb_iter ; i++ ) {
              // Decrement MaData
              md.setA( md.getA()-1 );
         System.out.println( Thread.currentThread().getName() + " a= " + md.a);
    public class MultiCore {
    volatile static MaData md;
    public static void main(String args[])
         try {
         // Data to be shared
         md = new MaData();
         MonThread mt1 = new MonThread( md, 0 );
         MonThread mt2 = new MonThread( md, 1 );
         mt1.start();
         mt2.start();
         mt1.join();
         mt2.join();
         } catch ( Exception ex ) {
         System.out.println( ex );
    This is the result i got:
    Thread-0 a= -734
    Thread-1 a= -801
    This ok for the first one but the second should obviously be 0. For me that mean that the volatile does not work and the threads just access to their cache on different cores. Can someone check that ?
    Thanks,
    Laurent

    Why should the second line obviously be zero?
    I don't think even if you make 'a' volatile that setA(getA() + 1) suddenly becomes atomic, because it becomes:
    int temp = getA();
    // if other thread update a, temp does not get updated
    temp = temp + 1;
    setA(temp);So you'll need a synchronized in/decrement methods on MaData or use an AtomicInteger.

  • Using javascript in modified Aperture web page themes

    Thanks to the many well-written tutorials on the subject, I've been able to modify an existing Aperture web theme to export customized web pages that have the exact look I'm after. I've successfully copied the Stock theme, edited the detail and journal-gallery html along with the global.css files and merged with a professional template I purchased, so now my Aperture-generated galleries look just like the rest of the pages on my web site.
    Of course, there's always a problem:
    If I reference any Javascript from the Aperture template files, Aperture EXECUTES the script during the process of exporting the web pages, and includes the result of the Javascript execution in the rendered HTML. It does this IN ADDITION to correctly writing the Javascript reference to the rendered page. The end result is TWO of everything. An example will make this more clear:
    If I include the following line in journal-gallery.html:
    <script language="JavaScript" type="text/javascript" src="assets/scripts/sidebar.js"></script>
    and the file sidebar.js contains:
    document.write('Home
    document.write('<'t find a single reference to the use of scripts. CLEARLY APERTURE KNOWS ABOUT JAVASCRIPT AND EXPECTS TO FIND IT BECAUSE IT'S EXECUTING ANY SCRIPT IT COMES ACROSS!!!
    The goal of all this, of course, is what any large professionally-done web site strives for: I don't want to re-render all my static content (the photo galleries) every time I add or remove a link in the sidebar. Editing sidebar.js should be all that's required to change the links.
    Anyone?

    Sorry, I see that the Javascript snippets in my original post are being executing by the web browser when the message is read.
    The 2 lines of Javascript, cleverly (ahem) encoded, might be visualized:
    document (dot) write ( <html anchor tag>Home<close html anchor tag>);
    document (dot) write ( <html anchor tag>Site Map<close html anchor tag>);

  • Using the if-modified since http header

    I've a few questions regarding this header.
    1/ What is the point in using this header? Does it help with page ranking/hits?
    2/ Is if useful for static html pages or just for dynamic ones?
    3/ If it is useful for static pages, how do you add it? I.e exactly what code needs to added to the header? There seems to be quite a lot of discussion on the web about the merits or not of using this, but no examples of what code needs to be added.
    Any ideas?

    I hacked the Servlet myself so that it honors the if-modified-since header and returns HTTP-304 if the cached version is still ok.
    lg Clemens

Maybe you are looking for

  • HTML Viewer: Copying images+text to another component

    Hi folks, I'm working on a Java app for a research project where I'd like to be able to view a webpage in one panel (with some HTML viewer) and then be able to select pictures AND text from it (web browser-style), click a button, and have it copy the

  • Using custom code in SSRS PDF rendering

    Hi, I have a written some custom code ( a simple function to maintain a counter ) in SSRS Report properties. Everything works fine when I render the report in Report Viewer, but the custom code is not recognized when I render the report to PDF. What 

  • Built in speakers not working, no red light, 2011 MacBook Pro 15''.

    I have been having audio issues with my computer ever since I upgraded to Mountian lion, internal speakers are not an option in sound settings. the volume indicator appears grey not black and sound is not adjustable. I am guessing Software issue beca

  • Seeburger AS2 - connectivity

    Hello, is it possible to have one single certificate for both AS2 and SSL, using HTTPS protocol. if yes should we upload the certificates twice (AS2 & SSL)? Also when we sent some messages via AS2, the seeburger AS2 server seems to be closing the con

  • Web 2.0?

    I'm trying to redevelop my website and I see some websites that operate differently from the ones I design. They seem so much cleaner and display allot quicker. They are promoting their site as Web 2.0, does anyone know what that means? Here's my Web