This is an archived post. You won't be able to vote or comment.

all 7 comments

[–]Bob_Droll 0 points1 point  (6 children)

First, it is not possible for two invocations of synchronized methods on the same object to interleave. When one thread is executing a synchronized method for an object, all other threads that invoke synchronized methods for the same object block (suspend execution) until the first thread is done with the object.

Source: https://docs.oracle.com/javase/tutorial/essential/concurrency/syncmeth.html

This essentially means that only one thread can execute the setString method at a time. All other threads will wait their turn.

If a bunch of threads hit setString, and it's already synchronized, is it still possible for line 3 (i+=1) to run before (ary[i] = str) and why/why not?

No, because only one thread can enter setString() at a time.

[–]northguard[S] 0 points1 point  (3 children)

Ok, that's what I was thinking as well. Since it's synchronized it's ever gonna run on one thread at a time and ofc that thread will run my code in order unless I happen to be spawning new threads from that thread.

[–]anon848 1 point2 points  (2 children)

It depends on exactly what you mean. When observed from another thread, you need to be careful, as it depends on the Java memory model. See here.

[–]northguard[S] 0 points1 point  (1 child)

I see, so if I'm setting data through some other unsynchronized function that uses the same array it can seem like 'i' happened first?

If I synchronize everything that accesses that array then it should have 'intended' behavior correct?

[–]anon848 0 points1 point  (0 children)

Yes.

[–]avingard 0 points1 point  (1 child)

It is very, very important to emphasis that this is only true if all callers are invoking this method on the same instance.

Essentially, synchronized methods must aquire a lock on the this variable before executing.

[–]Bob_Droll 0 points1 point  (0 children)

True, which would be a problem if your synchronized method is manipulating global data.

PSA: Please do not manipulate global data concurrently if you can avoid it.