Sie sind auf Seite 1von 7

6/13/13

are final,volatile & immutable threadsafe? (Threads forum at JavaRanch)

Big Moose Saloon


A friendly place for programming greenhorns!
Search

Java FAQ

Recent Topics

Register / Login

A special promo: Enter your blog post or vote on a blogger to be featured in an upcoming Journal

JavaRanch Java Forums Java Threads and Synchronization

Author

are final,volatile & immutable threadsafe?


posted 6/2/2008 4:56 PM

Manish Thapliyal Greenhorn Joined: Aug 07, 2007 Posts: 17

Please clearly explain are final,volatile & immutable threadsafe with example?

Manish

Peter Chase Ranch Hand Joined: Oct 30, 2001 Posts: 1970

posted 6/2/2008 5:50 PM

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?

Betty Rubble? Well, I would go with Betty... but I'd be thinking of Wilma.<br /> <br />#:^P
www.coderanch.com/t/234230/threads/java/final-volatile-immutable-threadsafe 1/7

6/13/13

are final,volatile & immutable threadsafe? (Threads forum at JavaRanch)

Rob Spoor Sheriff Joined: Oct 27, 2005 Posts: 19230


I like...

posted 6/2/2008 7:23 PM

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:
view plain c opy to c lipboard print ?

N ote: T ext c ontent in the c ode bloc ks is automatic ally word- wrapped

0 1 . 0 2 . 0 3 . 0 4 . 0 5 . 0 6 . 0 7 . 0 8 . 0 9 . 1 0 . 1 1 . 1 2 . 1 3 . 1 4 . 1 5 . 1 6 . 1 7 . 1 8 . 1 9 . 2 0 .

p u b l i cc l a s sT e s ti m p l e m e n t sR u n n a b l e { p r i v a t ef i n a lS t r i n g B u i l d e rb u i l d e r=n e wS t r i n g B u i l d e r ( ) ; p u b l i cv o i dr u n ( ) { w h i l e( t r u e ) { b u i l d e r . a p p e n d ( ' a ' ) ; } } p u b l i cs t a t i cv o i dm a i n ( S t r i n g [ ]a r g s ) { R u n n a b l er u n n a b l e=n e wT e s t ( ) ; n e wT h r e a d ( r u n n a b l e ) . s t a r t ( ) ; n e wT h r e a d ( r u n n a b l e ) . s t a r t ( ) ; n e wT h r e a d ( r u n n a b l e ) . s t a r t ( ) ; } }

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".

SC JP 1.4 - SC JP 6 - SC WC D 5 How To Ask Questions How To Answer Questions

Peter Chase Ranch Hand Joined: Oct 30, 2001 Posts: 1970

posted 6/2/2008 7:35 PM

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 knownwww.coderanch.com/t/234230/threads/java/final-volatile-immutable-threadsafe 2/7

6/13/13

are final,volatile & immutable threadsafe? (Threads forum at JavaRanch)

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 Joined: Aug 07, 2007 Posts: 17

posted 6/3/2008 11:07 AM

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 ?

amitabh mehra Ranch Hand Joined: Dec 05, 2006 Posts: 98

posted 6/3/2008 12:34 PM

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 Joined: Aug 07, 2007 Posts: 17

posted 6/3/2008 12:43 PM

i have read it many times but its confusing for me . If you have understood then explain me .

www.coderanch.com/t/234230/threads/java/final-volatile-immutable-threadsafe

3/7

6/13/13

are final,volatile & immutable threadsafe? (Threads forum at JavaRanch)

amitabh mehra Ranch Hand Joined: Dec 05, 2006 Posts: 98 Manish Thapliyal Greenhorn Joined: Aug 07, 2007 Posts: 17

posted 6/3/2008 2:02 PM

What part are you not able to understand in the article?

posted 6/3/2008 2:08 PM

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 Joined: Dec 05, 2006 Posts: 98

posted 6/3/2008 3:20 PM

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.

satishkumar janakiraman Ranch Hand Joined: May 03, 2004 Posts: 334

posted 6/3/2008 3:41 PM

Originally posted by amitabh mehra:

If you are a bit confused as to why immutable objects are not always thread 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
www.coderanch.com/t/234230/threads/java/final-volatile-immutable-threadsafe 4/7

6/13/13

are final,volatile & immutable threadsafe? (Threads forum at JavaRanch)

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 Joined: Dec 05, 2006 Posts: 98

posted 6/3/2008 4:40 PM

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. C heck the comments given in the article's page.

Satish, the writer has also clarified your point.

Peter Chase Ranch Hand Joined: Oct 30, 2001 Posts: 1970

posted 6/3/2008 6:01 PM

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.


Nicholas Jordan Ranch Hand Joined: Sep 17, 2006 Posts: 1282

posted 6/4/2008 6:06 AM

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
www.coderanch.com/t/234230/threads/java/final-volatile-immutable-threadsafe 5/7

6/13/13

are final,volatile & immutable threadsafe? (Threads forum at JavaRanch)

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 ]
"The differential equations that describe dynamic interactions of power generators are similar to that of the gravitational interplay among celestial bodies, which is chaotic in nature."

Jim Yingst Wanderer Sheriff Joined: Jan 30, 2000 Posts: 18670

posted 6/4/2008 7:10 AM

[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.

"I'm not back." - Bill Harding, Twister Nicholas Jordan Ranch Hand Joined: Sep 17, 2006 Posts: 1282

posted 6/5/2008 12:06 AM

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
www.coderanch.com/t/234230/threads/java/final-volatile-immutable-threadsafe 6/7

6/13/13

are final,volatile & immutable threadsafe? (Threads forum at JavaRanch)

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 fulldepth 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.

Granny's Programming Pearls "inside of every large program is a small program struggling to get out" JavaRanch.com/granny.jsp

subject: are final,volatile & immutable threadsafe?

Similar Threads Immutable classes Why cant a volatile variable final? Are context-parameters thread-safe? modifiers Marking a variable static final is thread safe
All times above are in your local time zone & format.T he current ranch time (not your local time) is Jun 13, 2013 03:31:47 .

Contact Us | Powered by JForum |

C opyright 1998-2013 Paul W he aton

www.coderanch.com/t/234230/threads/java/final-volatile-immutable-threadsafe

7/7

Das könnte Ihnen auch gefallen