views:

111

answers:

2

suppose we have multi processor machine and multi threaded application. If two threads have access to a synchronized method and they got executed at the same time which thread will gets the lock? or what will happen?

Thanks

+8  A: 
aioobe
I also don't think that there will be any "at the same time" at that level. One thread will get the lock, just by virtue of getting there first. No need for a coin toss.
Thilo
Yes, I agree...
aioobe
+2  A: 

The point is that there is no such thing as "at the same time". One of the two will get the lock, but you have no way to know which one.

There is no such thing "at at the same time" because, liberally speaking, a lock is something that chooses and executes the threads one at a time exclusively.

This is naturally accomplished in a pure monoprocessor system that can execute one instruction at a time. On multiprocessor systems usually there is some hardware device that "locks" the processors to prevent them from executing at the same time.

IlDan
Why not "at the same time"?
Feras
Why wouldn't it be something as "at the same time". We're talking about a multi-processor hardware...
aioobe
But the code that is managing the lock must be serializing somehow.
Thilo
@Feras, aioobe: Even in a multi-processor system, there are operations that can not execute concurrently (see http://en.wikipedia.org/wiki/Atomic_(computer_science)#Primitive_atomic_instructions ) and any implementation of sychrnonized must necessarily use such operations to ensure that no two threads enter the lock at the same time.
meriton
Yes, sure, that's the point of a lock. I (and I suspect the Feras as well) was asking about the case in which two threads *asks* for the lock at the same time. This must surely be possible...
aioobe
... but part of asking for that lock is executing the atomic instruction, and that part can't execute "at the same time".
meriton