« first day (4306 days earlier)      last day (618 days later) » 

12:00 AM
Staff meeting in the conference room in 3 minutes. (source)
 
 
6 hours later…
6:05 AM
I'm reading Java concurrency in practice. It says that both get and set should be synchronized. Reason for set is obvious to avoid value of one thread being overwritten. Reason of get also seems obvious to avoid reading stale values.

I was trying to construct an example for this stale reading situation by having nonsynnchronized get and synchronized set method, has anyone done this before?
 
@Akki Hi reading Java concurrency in practice, I'm Oak!
 
6:16 AM
My initial attempt looks something like this
a class having an int field, one non synchronized get method, one synchronized set method

public class MutableInteger {
private int value;

public int get() {
return value;
}

public synchronized void set(int value) {
this.value = value;
}
}
another class having main method to construct a situation where I can see stale reading causing problems

public class MutableIntegerExample {
public static void main(String[] args) throws InterruptedException {

for (int i = 0; i < 40; i++) {
MutableInteger mutableInteger = new MutableInteger();

Runnable t1 = () -> System.out.print(mutableInteger.get() + ", ");
Runnable t2 = () -> mutableInteger.set(20);
Runnable t3 = () -> mutableInteger.set(30);

Thread threadA = new Thread(t1);
Thread threadB = new Thread(t2);
as expected, I get different values printed. I believe the reason for that is no fixed ordering of starting threadA, threadB, threadC rather than stale reading.
Since, even with synchronized get method, I see different values printed.
I was then trying to fix the execution of these threads, but I'm suspecting, I'm moving away from constructing stale read example which I wanted to read in first place.
 
 
2 hours later…
8:23 AM
@Akki sounds weird as a rule of thumb
and in your case, synchronized has 0 value
setting a field is an atomic operation, which means synchronizing it has no benefit
synchronizing (or locking) is beneficial if you have several statements that assume behaviour from the others
for example:
if (myInt.get() > 0)
{
    return new ArrayList<>(myInt.get()); // assumes that the result is greater than 0
}
however, because these are two separate statements, their combined behaviour is non-atomic
other threads can mess with the value in between those two calls
a thread safe approach is to either lock other threads out during the entire operation, or avoid calling the get multiple times
preferably the latter:
var size = myInt.get();
if (size > 0)
{
    return new ArrayList<>(size); // knows that the size is greater than 0
}
some operations where you only have one statement, are actually multiple operations as well... so running those are also not thread-safe statements
for example:
i++;
which is actually:
i = i + 1;
you first read i then sum it with 1 , then another thread changes the value of i, then you set the value of i to the incremented value
public void Foo() throws InterruptedException
{
	class WrappedInteger
	{
		int value;

		/*synchronized*/ void increment()
		{
			value++;
		}
	}

	var i = new WrappedInteger();

	var t1 = new Thread(() -> {
		for (int j = 0; j < 500_000; j++)
			i.increment();
	});
	var t2 = new Thread(() -> {
		for (int j = 0; j < 500_000; j++)
			i.increment();
	});

	t1.start();
	t2.start();
	t1.join();
	t2.join();

	Assert.assertEquals(1_000_000, i.value);
}
this is a common example
this is a nice set of puzzles related to multithreading and thread-unsafe operations
 
8:53 AM
Yes setting is an atomic operation, writing one value there, but if an instance of mutable integer is going to be present between multiple threads, it would require synchronization of setter methods so that writing values in fields are serialized and at a given time only one thread writes the value in field
I guess that's the use case for that
similarly it's also advised to have synchronization on getter method too
to avoid any stale reads
Checkout this answer, he's quoting the part in book related to which I'm here
 
> but if an instance of mutable integer is going to be present between multiple threads, it would require synchronization of setter methods so that writing values in fields are serialized and at a given time only one thread writes the value in field
it is atomic
you do not need synchronization
 
9:10 AM
I cant seem to reproduce the 64-bit issue they talk about though
tbf, "Java concurrency in practice" should just be "use immutable shared data and keep mutable data non-shared"
why let multiple threads fight over who gets to read and write data? let them read and write their own data and combine in the end
if you do need shared mutable data, use mutable data that someone else wrote the management stuff for
such as the existing concurrent collections
when you use locking yourself, you probably did something wrong in the design phase
 
10:06 AM
@Wietlol Okay, any idea then why there is such example in book
 
ancient java runtimes perhaps
by essence of behaviour, both examples are 100% multi-thread-safe
 
MutableInteger in Listing 3.2 is not thread safe because the value field is accessed from both get and set without
synchronization. Among other hazards, it is susceptible to stale values: if one thread calls set, other threads calling get
may or may not see that update.
We can make MutableInteger thread safe by synchronizing the getter and setter as shown in SynchronizedInteger in
Listing 3.3. Synchronizing only the setter would not be sufficient: threads calling get would still be able to see stale values.
 
by essence of distribution, the first example has an undetermined delay
 
This is quoted as description of both examples
 
generally speaking, you dont have to worry about that delay
 
10:15 AM
Yes, but I just wanted to understand the concept
It says that `Synchronizing only the setter would not be sufficient: threads calling get would still be able to see stale values.`
I was particularly trying to create an example of this situation
 
you could try, but I doubt you would succeed in recreating the potential issue
 
10:31 AM
ah, I managed to reproduce the issue
	static boolean done = false;

	@Test
	public void testDone() throws Exception
	{
		var t = new Thread(() -> {
			while (!done) ;
			System.out.println("Exited loop");
		});
		t.start();

		Thread.sleep(100); //wait for JIT compilation
		done = true;
		System.out.println("done is true");
		t.join();
	}
this will print "done is true" and then wait forever
the values are thread safe, but they are not always 100% up to date
there is a delay before the second thread (t) will read the new value of done
that delay is "solved" by making getters and setters to the field synchronized
however, that is ancient java
the newer solution is to make the field volatile
(still using getters and setters, but they should not be synchronized)
take a look at the AtomicInteger class
the get method is not synchronized
but the value it returns is from a volatile field
generally speaking, the new done value will be shared to the other threads as soon as the main thread has done enough writing of shared variables to distribute their new values in bulk
 
the values are thread safe, but they are not always 100% up to date
How can we say that values are thread safe?
 
but if they never do anything else, it doesnt really update anything
 
the newer solution is to make the field volatile
Yes volatile would be correct in this example
 
the values are thread safe because you never read incorrect values from the variable
there is some talk about 64-bit values not being thread-safe where you can read half of the value from before it was set and half from after it was set
but I cant reproduce that issue
 
there is some talk about 64-bit values not being thread-safe where you can read half of the value from before it was set and half from after it was set

yes get and set operations are not atomic except for 64 bit non volatile double and long variables
 
10:42 AM
get and set operations are* atomic except for 64 bit non volatile double and long variables
 
@Wietlol Yes corrected it
 
no, it was correct the first time
 
Ah ye smy bad
reason: jvm is permitted to treat 64 bit read/write as 2 separate 32 bit read write operations
so if multiple threads come in picture and read/write are happening in diff threads, it's possible to get unexpected value during read
But again, problem comes when we want to replicate the example
 
yes
the delay problem is usually not that big of an issue
it is only an issue if you create code specifically to show that it can happen
once you properly join threads, even non-volatile data is shared appropriately
 
Yes, I'm looking to actually see how it can happen
 
10:47 AM
the invalid values would be a problem... if it were true, which I still doubt
this article explains how it could happen in theory
and posts an example... that fails to showcase it :)
 
more for the mutable integer example that I showed you earlier in pic
 
at least on my machine
but then again
in modern software engineering, we just are smarter and avoid shared mutable data
if you were to create a pull request and you used either volatile or synchronized keywords, I would reject it as you are either using keywords incorrectly, or you have shared mutable data
this book and these language features are mostly aimed at old coding habits
mostly habits before multithreading was introduced
but now, we just write better code
 
Okay
 
you want a count from 0 to 1.000.000?
private int countTo1MillionFast_old()
{
	var i = new int[]{0};

	var t1 = new Thread(() -> {
		for (int j = 0; j < 250_000; j++)
			i[0]++;
	});
	var t2 = new Thread(() -> {
		for (int j = 0; j < 250_000; j++)
			i[0]++;
	});
	var t3 = new Thread(() -> {
		for (int j = 0; j < 250_000; j++)
			i[0]++;
	});
	var t4 = new Thread(() -> {
		for (int j = 0; j < 250_000; j++)
			i[0]++;
	});

	t1.start();
	t2.start();
	t3.start();
	t4.start();
	try
	{
		t1.join();
		t2.join();
		t3.join();
		t4.join();
note that the first one is broken and needs synchronization to fix it
while the second one just works
(on a side note, counting to 1.000.000 is not really an interesting use case)
 
Okay
 
 
12 hours later…
11:01 PM
uses java.io.File
 

« first day (4306 days earlier)      last day (618 days later) »