Results 1 to 3 of 3
  1. #1
    simo_mon is offline Member
    Join Date
    Dec 2008
    Posts
    50
    Rep Power
    0

    Default Volatile keyword still relevant ?

    Hi ,

    I got told the other day by another developer that the use of the volatile keyword was outdated and in the more recent versions of java was in fact implicit.

    From my understanding you use the volatile key word to
    - make sure that the variable/object is stored in ram
    - avoid potential caching issues

    can anyone please confirm or deny that the use of the volatile keyword is no longer required ?

    Java Code:
    old way 
    
    public class ThreadSafeCounter 
    {
    
        private volatile int count = 0;
    
        public ThreadSafeCounter (){}
    
    
        public synchronized void incrementCount(final int amount)
        {
    
               count+=amount;
    
        }
    
    
    }


    Java Code:
    new_ way ???
    
    public class ThreadSafeCounter 
    {
    
        private int count = 0;
    
        public ThreadSafeCounter (){}
    
    
        public synchronized void incrementCount(final int amount)
        {
    
               count+=amount;
    
        }
    
    
    }
    thanks

  2. #2
    eRaaaa is offline Senior Member
    Join Date
    Oct 2010
    Location
    Germany
    Posts
    787
    Rep Power
    5

    Default Re: Volatile keyword still relevant ?

    Your example is very bad for showing a good volatile use :-)
    I think that can be very useful if you are using it right.
    Java Code:
    class Counter { 
      private volatile int value; 
      public              int getValue()  { return   value; } 
      public synchronized int increment() { return ++value; } 
      public synchronized int decrement() { return --value; } 
    }
    getValue must not to be synchronized if you are using volatile!
    a) value = int = atomicity is guaranteed
    b) visibility is guaranteed too because of the use of volatile!
    the other methods however must be synchronized (aren`t atomar)

  3. #3
    simo_mon is offline Member
    Join Date
    Dec 2008
    Posts
    50
    Rep Power
    0

    Default Re: Volatile keyword still relevant ?

    thank you for your response,

    i need to do some more reading

    :)

Similar Threads

  1. Replies: 1
    Last Post: 12-08-2011, 05:31 AM
  2. Keyword : volatile
    By peiceonly in forum Advanced Java
    Replies: 13
    Last Post: 11-17-2010, 12:47 PM
  3. transient vs volatile
    By waqar100 in forum New To Java
    Replies: 2
    Last Post: 06-14-2010, 10:21 AM
  4. Replies: 2
    Last Post: 03-27-2010, 09:01 AM
  5. use of volatile
    By venkatallu in forum New To Java
    Replies: 3
    Last Post: 09-23-2008, 09:59 PM

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •