Michael Farragher

+ Follow
since May 01, 2019
Cows and Likes
Total received
In last 30 days
Total given
Total received
Received in last 30 days
Total given
Given in last 30 days
Forums and Threads
Scavenger Hunt
expand Ranch Hand Scavenger Hunt
expand Greenhorn Scavenger Hunt

Recent posts by Michael Farragher

I read that "Immutable objects, on the other hand, can be safely accessed even when synchronization is not used to publish the object reference"

So if I've got the following immutable class

and I write

does this mean I've still got to check for null when another thread accesses a  ?


Hi Stephen,

Can direct you to Java Concurrency in Practice, pages 50 and 51.

If you look at class Holder on page 51, that is similar to the first class I listed - an int set in the constructor and then read in another method.

If you look at the footnote at the bottom of page 50, it says "The problem here is not the Holder class itself ..."
If I've got

Is this class thread safe ? From my reading I would suggest it was.

But if I've got

This class isn't thread safe.

Why is there a difference between initialising something in a constructor and in a setter ?



Thanks for getting back to me, Campbell.

If I can direct you to https://inbravo.github.io/docs/refer/java-concurrency.pdf

If you scroll to Chapter 3, in particular the paragraph under 3.1 Visibility, it says :

In general,there is no guarantee that the reading thread will see a value written by another
thread on a timely basis, or even at all. In order to ensure visibility of memory
writes across threads, you must use synchronization.

Doesn't this clash with what you've just said ?


I didn't think that changes made by one thread were visible to other threads unless you had synchronization in place ?

Say we have this class :

This class isn't thread safe.

Say we have an instance of this class and thread A executed the set method with a value of 5, then 5 hours later thread B executed the accessor method, we don't necessarily get to read the 5 that was previously set.

As well as preventing race conditions, I thought synchronization was necessary to allow us to read the most recent writes ?
Thanks for the response, Piet !

But isn't the thread that does the increment different to the thread that prints out the value ?
If one thread is incrementing sheepCount2 and another thread is printing its value, and we don't have appropriate synchronization in place, how can the answer be B ? Surely the answer must be C ?
That said, every time I've executed the code it always prints 100 100.

Can someone explain ?