MrG
MrG

Reputation: 5287

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?

Upvotes: 18

Views: 14289

Answers (7)

Tuğrul Karakaya
Tuğrul Karakaya

Reputation: 101

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){

        }
    }
}
}

Upvotes: 0

Hardcoded
Hardcoded

Reputation: 6494

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);)

Upvotes: 28

Niklas Rosencrantz
Niklas Rosencrantz

Reputation: 26644

I always leave syncs to app server or engine unless defining own intensity

Upvotes: 0

gustafc
gustafc

Reputation: 28865

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

Are you by any chance using the list as a queue, i.e., 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.

Upvotes: 0

Stephen C
Stephen C

Reputation: 718926

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.

Upvotes: 12

Varun
Varun

Reputation: 1004

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.

Upvotes: 3

Conrad Meyer
Conrad Meyer

Reputation: 2887

Yes.

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

Upvotes: -1

Related Questions