Mutex access of synchronized blocks

230 Views Asked by At

I have code that contains a synchronized block within a loop, something like that

while (true) {
    synchronized (SOME_MUTEX) {
            //some more code here
   }
}   

There is another thread that is running code that is synched with the same mutex. The thread above only reads, the other one only writes. the writing thread is being starved, and so updates don't come through. that would be fine even for a second or two, but the writing thread seems to be left out indefinitely.

I know with certainty that while this loop executes, the other thread also tries to get the mutex, and I do understand why it doesn't receive it while the above thread is executed, except for the times where the while loop reaches its end, and starts over a new iteration.

At this point the mutex should be release, shouldn't it? Shouldn't the other thread receive it at this point?

Thank you

1

There are 1 best solutions below

2
On

while loop reaches its end, and starts over a new iteration. at this point the mutex should be release, shouldn't it ?

Yes

shouldn't the other thread receive it at this point ?

No. The two threads have equal chances to acuire the lock, so the other thread may never get access to the synchronized block.

In order to give you meaningful advice, we need to know your goal. For example, if you have a variable inside the synchronized block which carries some data which has to be read by the other thread before the first thread writes new data into the variable, then you have to declare another boolean variable which tells if the variable is available for writing, and the first thread should wait in a loop until it becomes true. In fact, this is a queue with capacity of 1, so better use a ready-made implementation like ArrayBlockingQueue.

APPENDED

"two threads have equal chances to acuire the lock" - actual chances depend on environment - how O/S works and how busy processors are. When closing brace of the synchronized statement is reached, the other (blocked) thread is moved from the queue to the monitor to the queue to processors. If there is an available processor, it immediately starts to try to acquire the lock. Meanwhile, the first thread goes to the start of the loop and also tries to acquire the lock. Since the first thread is already on a processor, it has better chances, unless some external interrupt on its processor occur (from hardware timer, or any other device).

But for a programmer, all this has little sense. He must provide correct functioning of the program in both cases, no matter what probability that cases have. This is why I first wrote that threads have equal chances.