• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Ron McLeod
  • Paul Clapham
  • Devaka Cooray
  • Tim Cooke
Sheriffs:
  • Rob Spoor
  • Liutauras Vilda
  • paul wheaton
Saloon Keepers:
  • Tim Holloway
  • Tim Moores
  • Mikalai Zaikin
  • Carey Brown
  • Piet Souris
Bartenders:
  • Stephan van Hulst

volatile and static keywords

 
Greenhorn
Posts: 10
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
can any one tell me, what is the difference between volatile and static keywords.

thanks in adv.
 
Greenhorn
Posts: 12
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
if you declare a variable as static ,

it will be shared and seen by all objects of a class

::::::::::

if you declare a variable as volatile ,

it will be shared and seen by all threads of an object
 
Marshal
Posts: 79809
388
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
A question which belongs on the beginners' forum.
Static has been discussed many times on this forum.
  • Static code is loaded before the clas is instantiated and stays in memory until the JVM exits (as opposed to instance members which are loaded and unloaded: "dynamic" code),
  • each class has one copy of each of its static members in memory,
  • Each instance of the class has access to that single static memory location,
  • the single member is the same for every instance,
  • but a static member does not have access to instance members (it has no way of knowing where they are located), nor the keyword this and super.

  • Volatile means that the value of a variable is liable to change suddenly, and it instructs methods using a volatile member to update it immediately before use. I have never actually seen it used.

    CR
     
    Ranch Hand
    Posts: 1970
    1
    • Mark post as helpful
    • send pies
      Number of slices to send:
      Optional 'thank-you' note:
    • Quote
    • Report post to moderator

    Originally posted by Campbell Ritchie:
    Volatile means that the value of a variable is liable to change suddenly, and it instructs methods using a volatile member to update it immediately before use.



    Sort-of.

    It says that several threads may be interested in the value, so threads must not keep their own local copies with different values. When the value is changed in one thread, all other threads must see it straight away.

    It's a cheapo alternative to synchronized, giving a particular type of thread-safety. It may give performance or conciseness benefits compared to synchronized.

    Originally posted by Campbell Ritchie:
    I have never actually seen it used.



    It certainly does get used. It's not for absolute beginners (e.g. people who don't know what static means), though.
     
    Ranch Hand
    Posts: 32
    • Mark post as helpful
    • send pies
      Number of slices to send:
      Optional 'thank-you' note:
    • Quote
    • Report post to moderator
    Does the combination of volatile and static make sense?

    e.g. I have a static attribute that I know is going to be shared between lots of threads, some of which will update it. Will the JVM ensure visibility of changes to all threads just because it is declared static (i.e. implying the volatile modifier), or do I need to be extra safe and declare it a 'static volatile'?

    If so, surely all mutable static fields in a multi-threaded application should be declared static volatile? Except I've never seen this done.
     
    Bartender
    Posts: 4179
    22
    IntelliJ IDE Python Java
    • Mark post as helpful
    • send pies
      Number of slices to send:
      Optional 'thank-you' note:
    • Quote
    • Report post to moderator

    Xolani Nkosi wrote:Does the combination of volatile and static make sense?



    It does when the variable's use requires it to be volatile. I will explain more below.

    e.g. I have a static attribute that I know is going to be shared between lots of threads, some of which will update it. Will the JVM ensure visibility of changes to all threads just because it is declared static (i.e. implying the volatile modifier), or do I need to be extra safe and declare it a 'static volatile'?



    No. There is no special relationship between volatile and static. The JVM doesn't imply or assume volatility of static mutable objects. Nor, really, should it.

    If so, surely all mutable static fields in a multi-threaded application should be declared static volatile? Except I've never seen this done.



    No, I disagree. There are side affects to using volatile:

    Accessing a volatile field takes longer than accessing a non-volatile field (static or not). Consider a field to be stored in a 'central' repository. All Threads have access to this repository, but only work with variables in their own thread-specific repository. When a Thread needs a variable it can take the value out of the central repository, store it in the specific repository, then work with it locally. Then, at some point, it puts the value of the variable back into the central repository, effectively publishing so other Threads can see it. The JVM can optimize the movement of values into and out of this repository to make things run faster - it is quicker and safer to access the specific repository. There are certain boundaries which force a Thread to write all of the values it has in the Thread-specific repository into the central repository and to read values from that central location into the thread-specific one. These boundaries include synchronized blocks and now, any access to a volatile variable.

    So when a volatile variable is accessed or modified, not only does it require the Thread to pull the the volatile variables data directly from the central repository, and then to put it back in the next command (slightly slower than just accessing a local value), it also forces the Thread to do the same for ALL other variables that are being used. This is to enforce the 'happens-before' part of the volatile contract. So there could be a significant hit in performance in several use-cases.

    the volatile keyword is not a suitable replacement for synchronized blocks most of the time. It is really best used only for those cases when you have a simple and independent value you need to publish to other threads. Things like flags, counters, or oft-created and changed objects. The more threads you have changing the value, the less safe it is to rely on the volatile keyword and the more you likely you need to synchronize access. If the value is part of a calculation then generally it isn't good to use it either unless you also synchronize the calculation as well.
     
    Greenhorn
    Posts: 16
    • Mark post as helpful
    • send pies
      Number of slices to send:
      Optional 'thank-you' note:
    • Quote
    • Report post to moderator


    As i run the above code. all thread have its own copy of testValue variable. if thread 1 run its increment. at thread2 it value is 1.
    both with and without volatile keyword having same output.

    please anyone help me out.

    Thanks for your time.

     
    Sheriff
    Posts: 22810
    132
    Eclipse IDE Spring Chrome Java Windows
    • Mark post as helpful
    • send pies
      Number of slices to send:
      Optional 'thank-you' note:
    • Quote
    • Report post to moderator
    Compare lines 19+20 to line 24.
     
    Campbell Ritchie
    Marshal
    Posts: 79809
    388
    • Mark post as helpful
    • send pies
      Number of slices to send:
      Optional 'thank-you' note:
    • Quote
    • Report post to moderator
    getName().compareTo( . . . ) ???
     
    Rob Spoor
    Sheriff
    Posts: 22810
    132
    Eclipse IDE Spring Chrome Java Windows
    • Mark post as helpful
    • send pies
      Number of slices to send:
      Optional 'thank-you' note:
    • Quote
    • Report post to moderator
    At least it's better than using ==.
     
    Steve Luke
    Bartender
    Posts: 4179
    22
    IntelliJ IDE Python Java
    • Mark post as helpful
    • send pies
      Number of slices to send:
      Optional 'thank-you' note:
    • Quote
    • Report post to moderator
    The counter testValue is not static - there is a new variable for each ExampleThread you create. Since you create two ExampleThreads, you have two different testValue counters. So you should not expect the incrementing that happens in Thread 1 to affect the value in Thread 2.
     
    Greenhorn
    Posts: 2
    • Mark post as helpful
    • send pies
      Number of slices to send:
      Optional 'thank-you' note:
    • Quote
    • Report post to moderator

    It is really best used only for those cases when you have a simple and independent value you need to publish to other threads



    So imagine that "testValue" in the example above is a flag of some sort that we need other threads to watch and notice, is that the proper way to use it? If so then I don't understand the following:

    The counter testValue is not static - there is a new variable for each ExampleThread you create. Since you create two ExampleThreads, you have two different testValue counters. So you should not expect the incrementing that happens in Thread 1 to affect the value in Thread 2.



    I expected "Thread 2" to pick up the changes made by "Thread 1", and this is the source of confusion! If a volatile property is to be seen by ALL threads why "Thread 2" in "Akhtar''s example above could not see the volatile testValue? So what are those "other" threads that suppose to notice that the value of "testValue" has changed? Are we talking about other than "VolatileExample" threads? or threads that access a single thread instance of type "VolatileExampel"?

    The legend of Volatile continues, poorly documented and hardly understood.
     
    Steve Luke
    Bartender
    Posts: 4179
    22
    IntelliJ IDE Python Java
    • Mark post as helpful
    • send pies
      Number of slices to send:
      Optional 'thank-you' note:
    • Quote
    • Report post to moderator

    Daniel Nz wrote:... I don't understand the following:

    The counter testValue is not static - there is a new variable for each ExampleThread you create. Since you create two ExampleThreads, you have two different testValue counters. So you should not expect the incrementing that happens in Thread 1 to affect the value in Thread 2.



    I expected "Thread 2" to pick up the changes made by "Thread 1", and this is the source of confusion! If a volatile property is to be seen by ALL threads why "Thread 2" in "Akhtar''s example above could not see the volatile testValue? So what are those "other" threads that suppose to notice that the value of "testValue" has changed? Are we talking about other than "VolatileExample" threads? or threads that access a single thread instance of type "VolatileExampel"?

    The legend of Volatile continues, poorly documented and hardly understood.



    Look at this single threaded sample:


    At the end of the main method, what is the number stored in sample1.value? It will be 3, do you understand why? You have two different objects, sample1 and sample2. Each object has a variable named value. When you assign a value to the variable in one object (sample2.value) then you do not affect the value stored in the other objects' variable (sample1.value).

    This is exactly the same thing that is occurring in Akhtar's situation. He has two different Objects (which happen to be instances of the class Thread). Each object has its own variable, and therefore its own value. If you wanted to SHARE the value between threads then you should access the SAME variable - either using a shared object that both threads use, or by using a static variable, if that is what makes sense. The problem with Akhtar's code has nothing to do with the volatile key word, or static, or threads. It has to do with basic reference scope.
     
    Java Cowboy
    Posts: 16084
    88
    Android Scala IntelliJ IDE Spring Java
    • Mark post as helpful
    • send pies
      Number of slices to send:
      Optional 'thank-you' note:
    • Quote
    • Report post to moderator
    If you want to understand exactly what volatile is for, read the excellent book Java Concurrency in Practice.

    Coming back to the original question: static and volatile are two completely different things that don't have a lot to do with each other - it's a bit strange to ask what the difference is between them.
     
    Daniel Dhafir
    Greenhorn
    Posts: 2
    • Mark post as helpful
    • send pies
      Number of slices to send:
      Optional 'thank-you' note:
    • Quote
    • Report post to moderator
    I perfectly understand the difference between static variable and instance variable and why Sample1.value would be 3 at the end, this is basics.
    What I don't understand is what effect the keyword volatile would have on the variable and what this has to do with other threads accessing one copy of it?

    Can anyone think of perfect use-case of a volatile variable?

    Thanks,
     
    Bartender
    Posts: 15720
    367
    • Mark post as helpful
    • send pies
      Number of slices to send:
      Optional 'thank-you' note:
    • Quote
    • Report post to moderator
    In Java, each thread is free to cache static and member variables. The actual value of the variable is only written back to it's proper memory location at certain moments you can't always predict. This means that if you don't synchronize your class, and multiple threads access the same variable, they might end up seeing different values than what the value is expected to be after another thread has edited it.

    The volatile keyword simply tells threads they are not allowed to cache variables, so when another thread accesses the variable, it sees the most up to date version of it.

    When you synchronize a method, you're telling Java that when the method ends, it updates all the variables, so other threads that are about to work with the object see what they are supposed to see.
    This is why you don't see the volatile keyword a lot, because all of the work is usually done by the synchronized keyword.

    The only time you ever really use volatile is when you have a single field that is shared between many threads, and you're not accessing it through synchronized blocks.
    This case is rare.
     
    Greenhorn
    Posts: 4
    • Likes 2
    • Mark post as helpful
    • send pies
      Number of slices to send:
      Optional 'thank-you' note:
    • Quote
    • Report post to moderator
    Sometimes thinking of complicated things in a certain way helps to clarify use, even if the underlying mechanisms are constructed differently -- the Bohr model of the atom is a good example. I treat the JVM as being highly complex internally, as vendors are free to do all sorts of strange things to attempt to optimize performance, and thus I assume that there are all kinds of inter- and intra-thread strategies of local vs. glocal cache referencing and copying. So I came up with five rules of thumb that I program by:

    * Unless explicitly protected, at some point threads will tend to both clobber and miss each other's values
    * 'static' says it's "one copy for all instances", but I treat it as guaranteed "clean" only within a thread
    * 'synchronized' guarantees clean across threads, and is "relatively expensive" (performance-wise)
    * 'volatile' is also clean across threads, yet is "comparatively inexpensive", but might have a "lag time"
    * Atomic/Blocking variable is just as good as 'synchronized' for that variable, and is "mildly expensive"

    Remember -- these are the assumptions I use, not a declaration of architectural accuracy. What they do is let me program such that the end-resulting at-worst behavior is guaranteed. Basically, the heavier the synchronization, the more of a performance hit, and the lighter the synchronization, the less sure regarding the timing of noticing changes. But there's one axiom that the multi-threading programmer must know about the JVM, regardless of the vendor:

    NO SYNCHRONIZATION = NO INTER-THREAD VISIBILITY GUARANTEE

    There are other non-synchronous rules that do guarantee visibility -- things like certain "static final" declarations typical of constants -- but people are asking about regular, mutable variables here that take on multiple states throughout the life of a process, and this one axiom is vital.

    Here are some resulting strategies I use by applying these rules of thumb (numbered only for later reference):

    1. If I want one copy in a multi-threaded application, and not have to pass a reference, I use 'static'
    2. If I expect all (or many) threads to alter the value, I use explicit synchronicity (or Atomic/Blocking)
    3. If I expect one to write, but all others to read, I add 'volatile'
    4. If I expect read-often, but very, very, very few occassions to write, I add 'volatile'
    5. If absolutely every single read/write is utterly vital to the operation at the moment it occurs, I use Synchronized forms

    Notice that my use of 'static' has nothing to do with the protection of variable values, only whether I want a single variable representation when I'm not passing a direct variable reference. I use all the other forms when I'm trying to determine the protection and visibility of the values. Notice also on #5 that it refers to 2 concepts: Both the protection of the value, and the timing of the value change. This latter is a big part of the visiblity of changes -- it refers to when there's guaranteed to be inter-thread accuracy of reading.

    Visibility is very important: Operations that look atomic as a single Java statement, may require a dozen internal JVM operations to complete! Regardless of how it's accomplished within the JVM, I treat 'volatile' by a model of "visibility protection light" (again, it may not be accurate, but it's useful): I'm guaranteed to see the variable change, but I'm not exactly guaranteed on the timing. My thought-model can be concretely explained by an example (a completely hypothetical example):

    Take an operation that we'll assume requires 20 JVM operations to accomplish, and the JVM does it by copying
    the memory to a temporary area, operating on it, and then immediately writing the modified value back. Say Thread A requests it, and at operation 7, Thread B asks for the value and the multiprocessing system allows Thread B to quickly jump in to access the original memory. Under 'volatile', I'll get the value from the same location, but Thread A isn't finished updating, so Thread B sees the old value. In this program, eventually Thread B will later ask for the value again, and because Thread A has finished, it will see the new value in that memory location. Under 'synchronized', Thread B will get the result of Thread A's total work on every call, but for now is entirely locked out for the next 13 operations required to finish Thread A's request -- a definite performance penalty, but necessary if the semantics of the work demand it -- because threads are blocked out not just for writing, but also for reading. And it's not just writers blocking other writers, to assure modification protection -- WRITERS ALSO BLOCK READERS, AND READERS BLOCK EVERYBODY AS WELL! Again, for those of you nit-pickers: This is an operational model, not an architectural specification.

    So, what would I use for a bank ATM transaction application? Look at Result #5! I'd use 'synchronized' and Atomic/Blocking variables. Period.

    But where would I use 'volatile'? Before I give the "perfect use-case" that Daniel requests, let me provide an allegory.
    --------
    You're at a track meet, and the 100m race is underway. All the contestants are in the 'set' position, and all will wait for the starting gun. The gun goes off, and everybody starts running, but some are a little slower than others on the uptake, not reacting quite as fast to the signal -- but that's OK, it's even expected.

    Now, the starter determines after 1 second of running that somebody actually had a false start, and fires a second round. Each contestant reacts in time -- some faster than others -- to the interruption signal, and stops running. But it's OK that some go farther down the track than others, even after the signal, as all the results will be thrown away. One runner could even go to the finish line, which might be entertaining to the crowd, but doesn't hurt anything.
    --------

    On to the "perfect use-case": I have a program that divides up a massive amount of work that single-threaded would require 18 hours for larger customers. The program allows the administrator to set the number of threads, which can be slightly CPU-heavy, so I suggest 1.6 threads per CPU (so on a 4-CPU system, use 6 threads). There is a main process that sets everything up, including the threads: one Writer, and multiple Read&Compute (Readers). There's one more thread that's running -- the main program acts as a Master Monitor on the progress throughout operation, cleaning up when all the child threads are finished. Here are some variables, direct from this very popular program:

    * ArrayBlockingQueue workQueue: This is created and owned by the Master, and its reference is passed to all threads. Being internally synchronized, each Reader can't clobber the queue's manipulation by any other thread. Futhermore, that same internal synchronization means from a JVM perspective that when the Reader finishes computing and places the result on the queue, the finished work is guaranteed to be visible when the Writer picks it up from the queue. Both data protection and visibility are important here, so I used a Synchronized class form (Result #5). But I didn't need 'static' because the actual variable reference is explicitly passed as a parameter to the thread classes, so there's no need to explicitly declare that there's one copy; they all work on the passed reference.

    * static AtomicInteger mProcReady: Since they divide up the work, I don't want only a subset of threads to succeed; all must be able to get through their initializations. Each thread increments this counter when it's finished initializing and is ready to do work. The Master thread waits and polls until this counter reaches the number of threads it knows it spawned. It's absolutely vital that no increments are lost (see Result #5), because otherwise the Master will wait forever! So it's a shared value that's utilized directly through the variable name "mProcReady" and not through a reference, hence I need to declare 'static'. But it needs absolute protection (and the Master also wants to know quickly when conditions are right: idle time is wasted time!) so I used the Synchronized form of 'Atomic'. I could have used a latch variable to count down, but it's just easy for the Master thread to track the count-up, polling every second. NOTE: You CANNOT use an integer with "++" -- it's not guaranteed as an atomic operation, and thus one thread could clobber another's value in the middle of the multi-operation JVM's often use to implement "++" -- there's no protection! (But I could protect it by writing extra code such that the whole operation was explicitly executed with 'synchronize' -- but why clutter up the code? Why not just use something that internally does that for me anyway?)

    * static volatile boolean mStartGun: Once ready, each child thread goes into a wait-state, polling/sleeping until all the children are ready. This condition is signaled by the Master once it sees the Atomic Counter reach the desired state. In this case, all the children only read this value, and only the Master is changing the value (Result #3) -- and it changes only once, so there couldn't be any "lost changes" due to some ultra-quick intermediate states; it's off, and at some point it goes "ON" and stays that way. And so what if a child thread starts work a second later, either because of its own sleep/poll check, or because the visibility of the change is just ever so slightly slower than an explicit synchronized form? Just like the Track Meet start.

    * static volatile boolean mHaltGun: Throughout the processing (it may take hours), an error counter is tracked. If a threshold is reached, then the whole thing should be killed -- but cleanly. It turns out that the Halt Gun can be triggered by any thread, not just one thread. Like the Start Gun, we need a single Halt Gun (hence 'static'), but in this case there's likely to be only one write to it -- BUT IT'S OK if there's more than one, so 'volatile' by Result #4. Here's an important aspect of the decision: If there indeed occurs that there's more than one write to the variable (two threads hit an error at the same time, and both come to the conclusion at the same time that the threshold is exceeded), THEY CHANGE IT TO THE SAME VALUE. Thus, there can't be any lost intermediate states, because "clobbering" the value would always just set it to the correct desired value in the first place. And so what if any given thread takes a second longer than others to realize the Halt Gun signal went off? But why 'volatile' -- why not use a heavy form of synchronization, just to be sure? Because each thread tests the signal on every unit of work, and there's billions -- performance counts! No need for each thread to lock out the others just to read this thing 700 million times each! And who cares if due to the relaxed visibility that a thread happens to process just one more than it would have under full lock-out? Again, so what if one Track Meet competitor runs an extra stride further than the others when Halt is signaled?

    * static volatile long mMemCount: I also use 'static volatile' for a progress counter, where only the Write thread changes it (Result #3), but the other threads read it just to periodically flush work so that the system maintains general equilibrium. Again, it's called billions of times, so a less costlier form of work is advantageous. And so what if the Master thread's progress report to the log based on this counter skips a beat? It's a threshold-based reporting entry that contributes no work accomplishment in itself; if due to relaxed visibility the Master saw '499999' when it went in at the precise moment the Write process was changing it to '500000', who cares? The Master will report in another 10 seconds when it sees '500007', because that too exceeds the threshold -- no processing component will lose its vitality and blow up the moment every half-million records are processed, and half-million-and-one shoots by unnoticed. There's simply no need to lock all threads out of reading this value if it's also being modified by the lone thread that does so.

    This model works under even the heaviest load, and has proven itself time and again on any size system (1 to 32 processor). I've certainly given more than $0.02 here, and hopefully I've been able to contribute in a small way to answering the curious. And by the way, I don't know if I agree that this is "beginner" stuff -- I feel it's kind of "advanced beginner threading" stuff, but not "beginner Java" or "beginner programming" stuff, which I associate to the "beginner" forum.
     
    Campbell Ritchie
    Marshal
    Posts: 79809
    388
    • Mark post as helpful
    • send pies
      Number of slices to send:
      Optional 'thank-you' note:
    • Quote
    • Report post to moderator
    Welcome to the Ranch Useful answer, but it might be a bit late.
     
    Brad Jacobs
    Greenhorn
    Posts: 4
    • Mark post as helpful
    • send pies
      Number of slices to send:
      Optional 'thank-you' note:
    • Quote
    • Report post to moderator
    Thanks for the greeting. Yes, I had looked at the dates, and made a decision that the subject clearly resurfaces time and again, and my post is a mere 3 months after the last one. And I then added to it the fact that I indeed got here by virtue of making a Google search involving 'volatile', and it's clear to me that the subject is one that will probably never go stale, and that now the next person who does a similar Web search will have a more helpful response than the others I saw.

    But what I particularly wanted to do was to give the more veteran responders an example of a helpful response. Far too many give a 2-liner that for all intents and purposes gives the same cryptic mumbo-jumbo that the questioner had gleaned from other readings, and thus led to asking the question! Answers seem to assume hindsight; only somebody already familiar with more advanced aspects would have the knowledge to recognize the insight that the vetern answerer thinks he's giving. Yes, sometimes it would be good if people would read a little more documentation, and perhaps do a little more thorough a search before asking what is often a duplicate question. But the answer these veterans often supply is so bare-bones that it might as well say nothing more than, "It's that way, because it is." And I feel that far too often, the terseness communicates in such a way that flies in the face of the rather wonderfully put, single rule that The Big Moose Saloon presents to the joiner: "Be nice."
     
    Jesper de Jong
    Java Cowboy
    Posts: 16084
    88
    Android Scala IntelliJ IDE Spring Java
    • Mark post as helpful
    • send pies
      Number of slices to send:
      Optional 'thank-you' note:
    • Quote
    • Report post to moderator
    Wow, that's an elaborate first post! Welcome to the Ranch, Brad.
     
    Brad Jacobs
    Greenhorn
    Posts: 4
    • Mark post as helpful
    • send pies
      Number of slices to send:
      Optional 'thank-you' note:
    • Quote
    • Report post to moderator
    And thank you for the greeting as well.

    BY THE WAY, FOR ANYBODY READING THIS THREAD: Please, please, please heed Jesper's Jan. 30 advice! The book is one of the most well-written programming topic explications I've seen in years. It's quite clear and straight-forward. My decision to use volatile on the specific variables described in my post was a direct result of reading this book.
     
    Campbell Ritchie
    Marshal
    Posts: 79809
    388
    • Mark post as helpful
    • send pies
      Number of slices to send:
      Optional 'thank-you' note:
    • Quote
    • Report post to moderator

    Brad Jacobs wrote:And thank you for the greeting as well. . . . please heed Jesper's Jan. 30 advice! . . .

    You're welcome (sorry about the pun) and I have a copy of that book.
     
    Ranch Hand
    Posts: 1170
    Hibernate Eclipse IDE Ubuntu
    • Mark post as helpful
    • send pies
      Number of slices to send:
      Optional 'thank-you' note:
    • Quote
    • Report post to moderator
    I think I argued on these forums years ago that volatile had no practical value in Java. Perhaps in embedded Java. I think there were even some issues with the Java VM memory model prior to 1.5 that made it even more problematic.
     
    Brad Jacobs
    Greenhorn
    Posts: 4
    • Mark post as helpful
    • send pies
      Number of slices to send:
      Optional 'thank-you' note:
    • Quote
    • Report post to moderator
    From a language design standpoint, it certainly has practical value as a lighter form of synchronicity, and thus a performance option. But if performance is not of consideration, then it might be considered redundant (though it might appear to some as slightly more elegant in syntax than its substitutes). If program design results in a situation where it must be used under explicit synchronization in order to provide atomicity of operations, then it's completely superfluous.

    The argument that it is problematic under general implementation is a very good one; avoiding likely potential hazards is always a good design goal. Since I began using it for performance purposes beginning in late 1.5, I can't speak to that point in this case. But for a couple of years now, I haven't heard of any problems whatsoever on my very heavily used, large-scale implementations involving 'volatile' across UNIX flavors (at least, Sun, HP and IBM), RH Linux on multiple hardware platforms, and Windows servers.

    I should mention that these are batch processing programs, not involving user interfaces; introduction of GUI libraries presents its own perils, but I have found this true not because of any inherent, systematic problems with GUI libraries, but mostly because programmers don't employ carefully considered multithreading practices when utilizing such. In general, I think that multithreading is not well understood, and that most programmers think that it's merely a question of declaring something 'static' so that it's shared, or going a little further and explicitly synchronizing, but only where values are altered. Little attention seems to be afforded to issues of visibility or of atomicity.
     
    Greenhorn
    Posts: 17
    Java ME C++ Java
    • Mark post as helpful
    • send pies
      Number of slices to send:
      Optional 'thank-you' note:
    • Quote
    • Report post to moderator

    Ibrahim AlShehri wrote:if you declare a variable as static ,

    it will be shared and seen by all objects of a class

    ::::::::::

    if you declare a variable as volatile ,

    it will be shared and seen by all threads of an object



    Hi Ibrahim,
    what do you mean by static variable are shared by all objects of a class?

    Thank you,
     
    Master Rancher
    Posts: 5045
    80
    • Likes 1
    • Mark post as helpful
    • send pies
      Number of slices to send:
      Optional 'thank-you' note:
    • Quote
    • Report post to moderator
    Mak: you do realize you're replying to a post from 2007, right? I doubt the poster is still around to answer.

    The original topic of this thread is about really basic information about two keywords that have absolutely nothing to do with each other. I don't know why this question was ever even asked. Better to go to Java in General - Beginner and search for "what is volatile" and "what is static" as separate topics.

    As for the discussion of volatile, I think it was almost completely useless prior to JDK 5, due to flaws in the memory model. It simply didn't do what it was designed to do. Nowadays it does work better, and it's occasionally useful, but not very. Most places where I might try to use it, something like AtomicInteger is much more useful. There is simply no way to do something like compareAndSet() with a volatile primitive, which severely limits the usefulness of the keyword.
     
    Mr. C Lamont Gilbert
    Ranch Hand
    Posts: 1170
    Hibernate Eclipse IDE Ubuntu
    • Mark post as helpful
    • send pies
      Number of slices to send:
      Optional 'thank-you' note:
    • Quote
    • Report post to moderator
    Like I said, those 'issues' were solved in 1.5. 1.5 has a new memory model. They weren't exactly solved, they just became irrelevant.

    It may be possible that 'good enough' works in practice. I'm not going to reargue it. I wasn't alone in my position. Volatile is not a lighter form of synchronization. Its not synchronization at all.
     
    Campbell Ritchie
    Marshal
    Posts: 79809
    388
    • Mark post as helpful
    • send pies
      Number of slices to send:
      Optional 'thank-you' note:
    • Quote
    • Report post to moderator
    And welcome to the Ranch , Mak Smash
     
    I don't even know how to spell CIA. But this tiny ad does:
    Gift giving made easy with the permaculture playing cards
    https://coderanch.com/t/777758/Gift-giving-easy-permaculture-playing
    reply
      Bookmark Topic Watch Topic
    • New Topic