• 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
  • Tim Cooke
  • Ron McLeod
  • paul wheaton
  • Jeanne Boyarsky
Sheriffs:
  • Paul Clapham
  • Devaka Cooray
Saloon Keepers:
  • Tim Holloway
  • Roland Mueller
  • Himai Minh
Bartenders:

are final,volatile & immutable threadsafe?

 
Greenhorn
Posts: 17
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Please clearly explain are final,volatile & immutable threadsafe with example?
 
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
Sounds like a directly lifted homework question to me. We don't do your homework, but maybe I can give some clues.

The keywords "final" and "volatile", plus the technique of immutable objects, are all things that can be used to ensure thread-safety. Of course, missing from this list is the most important keyword, "synchronized".

However, there is no magic way of writing thread-safe code without effort. You have to think what "thread-safe" means, in your particular application; what data structures will be accessed concurrently and what safeguards are needed?
 
Sheriff
Posts: 22853
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
Final can be a bit dangerous though when used with objects.

The object reference is final, but the object's internal state can still be changed. The following is NOT thread safe:

Sure, you are refined to only one StringBuilder object. But that can still change, and since StringBuilder is not thread safe neither is this code, even though there is a "final".
 
Peter Chase
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 Rob Prime:
The following is NOT thread safe



I'm not sure you can really say that a whole multi-threaded program, like your example, is "thread-safe" or not. Your program has a deliberate threading bug in it, which is not quite the same thing.

The term "thread-safety" normally refers to a class or module that is known-correct in single-threaded use. If you say it's thread-safe, that means that it can safely be used by multiple threads, without those threads having to take measures to protect it.

But a thread-unsafe class is not necessarily a buggy class, unless the author claims it is thread-safe. Many perfectly good classes are thread-unsafe, because there's no point making them thread-safe. Reasons for this might be: -
  • it makes no sense to use them in more than one thread
  • they usually form part of a larger data structure and it's the whole structure, rather than the individual objects, that should be made thread-safe.

  •  
    Manish Thapliyal
    Greenhorn
    Posts: 17
    • Mark post as helpful
    • send pies
      Number of slices to send:
      Optional 'thank-you' note:
    • Quote
    • Report post to moderator
    Peter,

    If this topic is so simple then why your answer is not clear.

    Actually my proble is :

    I have read that the final primitves are thread safe while object refrences do not ?
    And the immutable onjects are not thread safe.

    I am unable to understand the reason for the second one ?
     
    Ranch Hand
    Posts: 98
    • Mark post as helpful
    • send pies
      Number of slices to send:
      Optional 'thank-you' note:
    • Quote
    • Report post to moderator

    Originally posted by Manish Thapliyal:


    I have read that the final primitves are thread safe while object refrences do not ?
    And the immutable onjects are not thread safe.

    I am unable to understand the reason for the second one ?



    If you are a bit confused as to why immutable objects are not alwaysthread safe, perhaps you can get a hint in this blog: immuatability does not guarentee thread safety
    [ June 03, 2008: Message edited by: amitabh mehra ]
     
    Manish Thapliyal
    Greenhorn
    Posts: 17
    • Mark post as helpful
    • send pies
      Number of slices to send:
      Optional 'thank-you' note:
    • Quote
    • Report post to moderator
    i have read it many times but its confusing for me . If you have understood then explain me .
     
    amitabh mehra
    Ranch Hand
    Posts: 98
    • Mark post as helpful
    • send pies
      Number of slices to send:
      Optional 'thank-you' note:
    • Quote
    • Report post to moderator
    What part are you not able to understand in the article?
     
    Manish Thapliyal
    Greenhorn
    Posts: 17
    • Mark post as helpful
    • send pies
      Number of slices to send:
      Optional 'thank-you' note:
    • Quote
    • Report post to moderator
    Its new JMM model & i am unable to understand the reodering & viblity terms.
    can you explain in simple language.

    Also how it can be posible that before the object is contructed you access a variable .
     
    amitabh mehra
    Ranch Hand
    Posts: 98
    • Mark post as helpful
    • send pies
      Number of slices to send:
      Optional 'thank-you' note:
    • Quote
    • Report post to moderator
    A memory model basically deals with how/when the variables/fields in the program are to be stored/retrieved from memory. For optimization purpose, the cache, compiler etc take liberties as when to move the variable value from/to the variable's assigned location. These steps are transparent to the user but might show up on multiprocessor systems.
    So, for optimization, old JMM allowed the compiler to do things like change the order of execution of some instructions or allow caches to write variables values back to main memory in some different order than what appears in the program till the symatics of the program is not changed.
    So this the reordering, visibility part that the article talks about.

    When an object is being created, then before the constructor is called, all the fields etc are initialized to the default values. These are later set to the desired values in the constructor. So in between, it is possible for some other thread to have the field value as the default value rather than the set one.
     
    Ranch Hand
    Posts: 334
    • Mark post as helpful
    • send pies
      Number of slices to send:
      Optional 'thank-you' note:
    • Quote
    • Report post to moderator

    Originally posted by amitabh mehra:


    If you are a bit confused as to why immutable objects are not alwaysthread safe, perhaps you can get a hint in this blog: immuatability does not guarentee thread safety

    [ June 03, 2008: Message edited by: amitabh mehra ]





    The example given in the article is not a immutable class. It is a mutable class. If you want to write a immutable class, all object attributes must be final and private. Public setter methods should not be provided. Check the comments given in the article's page.
     
    amitabh mehra
    Ranch Hand
    Posts: 98
    • Mark post as helpful
    • send pies
      Number of slices to send:
      Optional 'thank-you' note:
    • Quote
    • Report post to moderator

    Originally posted by satishkumar janakiraman:




    The example given in the article is not a immutable class. It is a mutable class. If you want to write a immutable class, all object attributes must be final and private. Public setter methods should not be provided. Check the comments given in the article's page.



    Satish, the writer has also clarified your point.
     
    Peter Chase
    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 Manish Thapliyal:
    If this topic is so simple then why your answer is not clear




    I didn't say it was simple.
     
    Ranch Hand
    Posts: 1282
    • Mark post as helpful
    • send pies
      Number of slices to send:
      Optional 'thank-you' note:
    • Quote
    • Report post to moderator

    Originally posted by Manish Thapliyal:
    If this topic is so simple then why your answer is not clear.


    It is not a simple topic. The book may be making a gentle landing in a Briar Patch.

    I have read that the final primitves are thread safe while object refrences do not ? And the immutable onjects are not thread safe.


    final, or immutable ( which is what the word final does, not an actual keyword ) does not make anything Thread Safe

    I don't know where you got the book but either you are mis-reading what the book says or you need to get another book.
    [ June 03, 2008: Message edited by: Nicholas Jordan ]
     
    Wanderer
    Posts: 18671
    • Mark post as helpful
    • send pies
      Number of slices to send:
      Optional 'thank-you' note:
    • Quote
    • Report post to moderator
    [satish]: The example given in the article is not a immutable class. It is a mutable class. If you want to write a immutable class, all object attributes must be final and private. Public setter methods should not be provided. Check the comments given in the article's page.

    [amitabh]: Satish, the writer has also clarified your point.


    No, the writer made a slightly different point, because the writer used a slightly different (weaker) definition of "immutable". The writer gave an example of a class that was "immutable" but its fields are not final. Such a class is not truly immutable - not according to what Satish wrote. Or according to me. A truly immutable class is one whose fields are all final, whose fields are either primitive or also immutable types, and the class is being run using JDK 5 or later. (I could also say that it has no setters or other mutator methods, but that's not necessary - it follows from making the fields final.)

    [Nick]: final, or immutable ( which is what the word final does, not an actual keyword ) does not make anything Thread Safe

    A truly immutable class is thread-safe in all respects, no matter how you use it. (Um, well, aside from some nasty things you might do with reflection maybe...) The keyword final is necessary but not sufficient to make this happen. You are not doing anyone any favors by blurring the distinction between final and immutable.
     
    Nicholas Jordan
    Ranch Hand
    Posts: 1282
    • Mark post as helpful
    • send pies
      Number of slices to send:
      Optional 'thank-you' note:
    • Quote
    • Report post to moderator

    Originally posted by Jim Yingst:
    [Jim]: A truly immutable class is thread-safe in all respects, no matter how you use it. (....) The keyword [b]final is necessary but not sufficient to make this happen. You are not doing anyone any favors by blurring the distinction between final and immutable.


    I took the title of the post as my frame for the question, there are several intervening points made which work toward the definitive conclusion you make available for original poster, drawing from the work of others to achieve that clarity. Yes, my wording can be constructed to motivate examination of how everyting in a class must be final for that class to be threadsafe, but consider a function call taking an Object. ( The unsync() ArrayList comes to mind as a correct example for discussion ) If that class method is marked final it would seem to me there would still be a way to code a test case such that two threads could work on one instance - raising the issue of mutability even though all class methods and primitives are marked final.

    I thought my wording you cite makes the distinction that final is a keyword, mutable is a nomenclature for speaking about what final does. My choice of the word anything may have been more appropriately 'does not make everything thread safe. I used the choice anything as the more casual connotation which you and I as native speakers would construe the word, seeking to attain informality with a non-native speaker of our language who had asked for full-depth treatment.

    I tried to do the example Rob codes - a while back - but gave up on it due to compiler errors about dispatching multiple start()'s on a single instance but moved on to more produtive areas of work. Peter Chase follows with the counter example and Manish comes back with if it is so simple why is it not so simple, so I thought I'd take a little heat to walk the poster through the thickest part of the briar patch.
     
    reply
      Bookmark Topic Watch Topic
    • New Topic