简体   繁体   中英

Ensure Java synchronized locks are taken in order?

we have two threads accessing one list via a synchronized method. Can we

a) rely on the run time to make sure that each of them will receive access to the method based on the order they tried to or

b) does the VM follow any other rules

c) is there a better way to serialize the requests?

No, synchronized will give access in any order (Depends on the JVM implementation). This could even cause Threads to starve in some scenarios.

You can ensure the order by using ReentrantLock (since Java 5.0) with the fair=true option. ( Lock lock = new ReentrantLock(true); )

No you cannot be sure that two calls to a synchronized method will occur in order. The order is unspecified and implementation dependent.

This is defined in the 17.1 Locks section of the JLS. Notice that is says nothing about the order in which threads waiting on a lock should gain access.

You can't rely on the order in which the particular method is called from each threads. If it is only two threads may be yes. But imagine if there are 3 threads and 1 thread already acquired access. The other 2 threads when they try to access will wait and any one of them can be awarded the access, and this does not depend on the order in which they called this method. So, it is not suggested to rely on the order.

c) is there a better way to serialize the requests?

Are you by any chance using the list as a queue, ie, does the usage pattern look something like this?

while (some condition) {
    synchronized(theList){
        anItem = get and remove an element from theList
    }
    do some work with anItem
}

If so, you may want to look at the BlockingQueue interface instead of using your own locking schemes. The implementations (like ArrayBlockingQueue ) have settings for fairness and more.

除非定义自己的强度,否则我总是将同步留给应用服务器或引擎

I have solved similar problem with couple of instrument. The problem I was trying to solve is Ping Pong Service. two thread one prints Ping and the other prints Pong. but They have to be SEQUENTIAL. (no double Ping or double Pong)

I will put one of the Implementation here but you can have a look other implementation (6 or 7 different way for now) https://github.com/tugrulkarakaya/pingpong

import java.util.concurrent.*;

public class Method2CyclicBarrier {

ExecutorService service;
CyclicBarrier c1 = new CyclicBarrier(2);
CyclicBarrier c2 = new CyclicBarrier(2);

public static void main(String[] args) {
    Method2CyclicBarrier m = new Method2CyclicBarrier();
    m.runPingPong();
}

public void runPingPong(){
    service = Executors.newFixedThreadPool(2);
        service.submit(() -> this.printPing(c1, c2));
        service.submit(() -> this.printPong(c1, c2));
}



public void printPing(CyclicBarrier c1, CyclicBarrier c2) {
    while(!Thread.currentThread().isInterrupted()) {
        try {
            c1.await();
            System.out.println("PING");
            c2.await();
        } catch (InterruptedException e) {
            Thread.currentThread().interrupt();
        }
        catch(BrokenBarrierException ex){

        }
    }
}

public void printPong(CyclicBarrier c1, CyclicBarrier c2){
    while(!Thread.currentThread().isInterrupted()) {
        try {
            c1.await();
            c2.await();
            System.out.println("PONG");
        } catch (InterruptedException ex) {
            Thread.currentThread().interrupt();
        } catch(BrokenBarrierException ex){

        }
    }
}
}

Yes.

If access to the list is via one synchronized method, concurrent requests from multiple threads will be serialized.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM