I used a synchronized block in the Solution constructor for all that logic, used a synchronized (this) in the first method and a synchronized (Solution.class) in the second method and the answer validated. What is the point of using both "this" and "Solution.class"?
I don't understand why this code worked haha
Under discussion
Comments (2)
- Popular
- New
- Old
You must be signed in to leave a comment
Guadalupe Gagnon
30 March 2020, 16:34
The task says that the two methods should simultaneously be accessed from different threads. If you used the same synchronize (this or Solution.class) on both of them, then when a thread accessed one, both would be locked. That would fail the condition. The synch block in the constructor wasn't needed.
Just to be sure, the use of synchronize only locks other blocks of synchronize with the same mutex. So if you had a block of synchronize(this), that does not mean that the entire object is locked and can't be used, only what is inside the synch block as well as any other synch blocks that are locked by the same.
+3
John
30 March 2020, 21:30
That was helpful, thanks! I didn't consider the fact that other methods with the same synchronized object ("this" in your case) would be blocked as well, but it makes sense why.
+1