[Logo]
Forums Register Login
Thread safety of this example.
Is there any reason to need to synchronize in this case (see comment in the code)?

no. Why would you think so?
 

Originally posted by Mr. C Lamont Gilbert:
no. Why would you think so?



I just ran across some code by someone with more recent threading experience than I have and I thought maybe I forgot something!

To me since this was all local it should be fine, but I've been away from threading for quite a while so...
No, the synchronized block doesn't make any sense, as every thread would creates its own stringbuffer object, anyway. There is no way two threads could try to get a lock on the same buf object.
 

Originally posted by Ilja Preuss:
No, the synchronized block doesn't make any sense, as every thread would creates its own stringbuffer object, anyway. There is no way two threads could try to get a lock on the same buf object.



I think his thoughts were that the object being passed in to method2 might be exposed to concurrent modification in other methods not seen in this example and locking it down this way would prevent it.

Again, I thought as you did but...
 

Originally posted by Darrin Smith:

I think his thoughts were that the object being passed in to method2 might be exposed to concurrent modification in other methods not seen in this example and locking it down this way would prevent it.



But the way the code is written, by synchronizing on the locally created buf object, there is no locking that would prevent it.
 

Originally posted by Ilja Preuss:


But the way the code is written, by synchronizing on the locally created buf object, there is no locking that would prevent it.



So maybe he is right in that a concurrent modification can take place to the SubObject passed in to method2, but instead of synchronizing on the StringBuffer, he should have used the SubObject reference itself?
Yes, synchronizing on the SubObject might possibly be useful, though it's hard to say without knowing more about how it's used. Whereas synchronizing on the StringBuffer is of no possible use to anyone.

I also note that the entire method2 could be shortened to:
and POOF! You're gone! But look, this tiny ad is still here:
Why should you try IntelliJ IDEA ?
https://coderanch.com/wiki/696337/IntelliJ-IDEA


This thread has been viewed 717 times.

All times above are in ranch (not your local) time.
The current ranch time is
Jul 20, 2018 20:22:43.