Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Intra-thread coherence [duplicate]

The code is simple.

// not annotated with volatile
public static int I = 0;

public static int test(){
    I = 1;
    return I;
}

There is a thread that invokes the method test.

Is it possible the method test will return the value '0'?

In other words, the reading of a shared variable maybe not see the modifying by the same thread.


update

The question just very simple, but I make its obscurity, I'm really sorry about it.

The a thread means a single thread.

And the question is duplicated with it.

like image 562
梁雨生 Avatar asked Jun 29 '26 10:06

梁雨生


2 Answers

Any answer that does not explain in terms on java language specification is only partially correct, if correct at all.

You need to make a clear distinction between actions that happens within a single thread and are tied together by program order and that in turn creates a happens-before connection, specifically via:

If x and y are actions of the same thread and x comes before y in program order, then hb(x, y).

That rule tells you that if you think about this code in single threaded world, it will always print 1.

And on the other hand, actions that create synchronizes with connections across different threads, and implicitly those create happens-before, via:

If an action x synchronizes-with a following action y, then we also have hb(x, y).

In your case, I is a plain field, as such every operation related to it is a plain store and/or a plain load. Such stores and loads do not created any connections at all according to the JLS. As such some thread that reads I can always read it as 0 if there is a writing thread involved.

like image 132
Eugene Avatar answered Jun 30 '26 22:06

Eugene


No, it will be 1 if no other thread is involved but the one that will invoke the method.

chrylis -cautiouslyoptimistic's answer is worth reading for an alternative scenario as well.

Two reasons:

  • I is just altered by its owner, and if the other thread just calls test(), there's no option for it to get a 0 as I's value.
  • The second thread won't read Class.I's value, but the result of the test() method. The assignation I=1 happens before the return so is guaranteed to offer the latest updated value (which has only been updated by the owner, once).
like image 29
aran Avatar answered Jul 01 '26 00:07

aran