Sebastien Sim
Sebastien Sim

Reputation: 1

Java Locking <What is wrong with this?>

The question here is: "Which of these choices will have the best performance for the theater of the thread safe choice?"

public static List<Lock> lockList = initializeLocks();
public boolean bookSeat(int seatNumber, int customerID){
    lockList.get(seatNumber).lock();
    try{
        Seat seat = listOfSeats.get(seatNumber);
        if(seat.isAvailable()){
            seat.setCustomer(customerID);
            return true;
        } else { return false; }
    } // end try
    finally { lockList.get(seatNumber).unlock(); }
}

vs

private static List<ReadWriteLock> lockList = initializeLocks();
public boolean bookSeat(int seatNumber, int customerID){
    lockList.get(seatNUmber).writeLock().lock;
    try{
        Seat seat = listOfSeats.get(seatNumber);
        if(seat.isAvailable()){
            seat.setCustomer(customerID);
            return true;
        } else { return false; }
    } // end try
    finally { lockList.get(seatNumber).writeLock().unlock; }
}

Thank you guys so much! From my understanding, both works but apparently from what I gathered from my Professor in school is that option 2 is the correct one, I don't understand why one is better than the other. Hope you guys can help! Thank you!

Upvotes: 0

Views: 38

Answers (2)

OldCurmudgeon
OldCurmudgeon

Reputation: 65811

The first just uses an ordinary lock, the second uses a write lock.

Ordinary lock - Exclusive

Once you have a lock, no other thread can grab another lock. This is essentially therefore an exclusive lock.

Write Lock - Exclusive for writes

Once you have a write lock, no other thread can grab another Write lock but they can grab a Read lock.

Read Lock - Co-operates with write locks

Once you have a read lock, other threads can take read locks. However, no write locks can be taken while a read lock is taken.

Essentially, between the read and write locks, ou can arrange for exclusive access while writing but a free-for-all if everyone is just reading.

Which of these choices will have the best performance for the theater of the thread safe choice?

Generally you will get better performance using read/write locking if you are reading and writing. The ordinary lock stops all access.

Upvotes: 1

Wakachopo
Wakachopo

Reputation: 149

The second method locks the resource only for writing, and not for reading. First method locks for both operations.

So the second lock permits another process to read the resource, while the first do not permit it. Although, first is a more expensive operation.

You can see things like this in official documentation: https://docs.oracle.com/javase/7/docs/api/java/util/concurrent/locks/ReadWriteLock.html#writeLock()

Upvotes: 0

Related Questions