0

I've just read some code, and notice there is some code with synchronized a local object. Could some one tell me what dose it mean when we do it since we just create a new local object, why should we lock it ?

list queue;
...

public send()
{
    entry = waitEntry();
    //add this object into the list
    queue.add(entry);
    ...
    synchronized( entry )
    {
        //do some sth
        entry.wait();
    }
}

then, when we receive the response, unlock this object

public receive()
{
    entry = list.get() <-- get the object we have sent before
    synchronized( entry )
    {
        entry.notify()
    }
}

As you see, I already lock the 'entry' before, how can I locked it again in receive() method ?

Thanks everyone.

dinhha471
  • 3
  • 1

1 Answers1

0

If you have multiple running thread that will access to the same ressource, you could have some concurrency issues, in your exemple the first thread will add the entry to a queue and then this thread must wait that the other code effect his action on this ressource. Since the two thread are executed at the same time, the receive method could read the entry ressource in the wrong state (before the send method perform on the ressource).

This is how i understand, i may be wrong. If you want more information about this kind of problem you should read articles about concurrency

Omegaspard
  • 1,828
  • 2
  • 24
  • 52