Make synchronized java queue calls?

I have read the oracle doc about synchronized methods and how they can inject locking into a multithreaded program, but there is one thing that is not clear to me. Are subsequent calls to already blocked methods in the queue?

Let's say we have a class:

class Astore {
    ...
    public synchronized void a() {
        doSomethingTimeConsuming();
    }
    ...
}

      

and 3 threads called astore.a ()

final Astore astore = new Astore();

Thread t1 = new Thread(new Runnable() {
    public void run() { 
        astore.a();
        doSomethingElse();
        astore.a();
    }
});
t1.start();

Thread t2 = new Thread(new Runnable() {
    public void run() {
        astore.a();
    }
});
t2.start();

Thread t3 = new Thread(new Runnable() {
    public void run() {
        astore.a();
    }
});
t3.start();

      

I'm not sure if I did this example correctly, but the point is that three threads access the same object at the same time with a synchronized method.

Will the order of operations be kept in the queue so that the calling threads are:

  • t1 (as it was called first)
  • t2 (called after T1)
  • t3
  • t1 again (he was busy doing what he was doing with A already at the time that another method was requested)

Is it safe to assume that this will be behavior, or is there no guarantee that it will be order (or worse, t2 and t3 can be called randomly)

What is the best practice when multiple threads might need to exchange data (e.g. a socket server with one thread for each active connection - I don't want 6 clients to time out waiting for the first to complete a huge load into a shared data structure)

+3


source to share


3 answers


No, it will not send method calls to the queue.

If the call is made from a thread that already has a lock (like a recursive call) then it will work as usual.



Other threads that are trying to force the lock to be able to make a call will hold it and wait until the lock is released.

Ordering is not guaranteed, use fair ReentrantLock if important.

+8


source


If you are using ReneterantLock instead of a synchronized block, there is a fairness parameter that you can set so that the thread that is waiting the most gets the lock when the lock is released by another thread, you can read more here



+2


source


folkol is correct.

Actually, it depends on the design of the machine (CPU)

Callers must wait until the resource is allocated to the CPU. The CPU then randomly selects one of the following callers and allocates a resource for it and blocks it (due to synchronicity) until the second caller completes its job.

0


source







All Articles