A_Carolan
A_Carolan

Reputation: 23

Java synchronized blocks using specific object reference

I'm using the code below to block concurrent access to an Auction object. It gets the object from a hash map so it operates on a wide range of different Auctions.

I've used a synchronized block with a reference to the individual Auction object chosen as the parameter. I'm under the impression that this holds the lock from the objects monitor and will block access to threads also using the same auction (until the first case has finished).

Can anyone confirm that this code is acting in a way that 1) If two thread both reference auction A then only one may proceed at time 2) If one thread references Auction A and another Auction B then they both proceed as they acquire different locks.

    //Get auction from hashmap
    Auction biddingAuction = (Auction) auctions.get(ID);

    //Check that auction is active
    if(biddingAuction != null)
    {
        //Acquire lock on Auction object
        synchronized(biddingAuction) {

       //Some code that alters values of Auction

       }

    } else {
        return "\nBid failed - no auction with an ID of " + ID + " was found\n";
    }

any clarity would be appreciated, thanks

Upvotes: 1

Views: 60

Answers (1)

JB Nizet
JB Nizet

Reputation: 691923

Can anyone confirm that this code is acting in a way that 1) If two thread both reference auction A then only one may proceed at time

No. Both threads would have to synchronize on the Auction to have that guarantee. If one thread doesn't synchronize, it can access the auction even if another thread holds its lock.

That's why such a way of doing is very fragile: if you ever forget to synchronize before accessing the Auction's mutable shared state (whether it write it or reads it), your code isn't thread-safe. A much cleaner way would be to make the Auction class itself thread-safe, by properly synchronizing the methods that access its shared mutable state.

If one thread references Auction A and another Auction B then they both proceed as they acquire different locks.

Yes. That is correct.

Upvotes: 1

Related Questions