How to execute synchronized code parallelly?

Sun Source

Suppose I have code below:

synchronized(someObject) {
  //do something
}

As far as I know, if someObject is not final, when it is re-assigned with another value while there is one thread inside synchronized block, it could cause parallel execution.

My question is, besides above situation, is there another way to execute the synchronized code in different threads simultaneously?

javamultithreadingthread-safetysynchronized

Answers

answered 6 months ago Jim Garrison #1

If the method doSomething() is not synchronized, and another thread invoked it directly and not through your synchronized statement, then yes, you could have two threads in the same code.

If you need to prevent this, make doSomething() synchronized. If it's not in the same class as the code you show, then you need to prevent it being accessible except through the synchronized statement in your example.

If you can guarantee it's not accessible (callable, i.e. private) any other way than through the synchronized statement then you're safe unless someone resorts to reflection (and there's no security manager policy set up to prevent it). With reflection a malicious developer could get around the protection and invoke the method directly. But you may not need to worry about that, you haven't specified if that is a concern.

comments powered by Disqus