Why is this giving me an IllegalMonitorStateException when all I'm doing is locking and then awaiting a condition?

50 views Asked by At

For context, this is a blackjack game so dealer, player, handvalue and other terms are coming from that.

obLock is a ReentrantLock and dealerDone is a Condition on that lock.

In the past, I have done this same method where I have had a static lock in the class which I use to lock a method/part of a method, await a signal from a condition and then unlock the method after I'm done

From my understanding, I should only be getting a IllegalMonitorStateException if I don't have possession of the oblock when I try to do the await Condition. This kind of makes sense as I'm locking it on both sides as I'm awaiting/signaling, but this is how I've done it in the past and is how I was taught.

Here is my code for awaiting the condition

obLock.lock();
        try {
            dealerDone.await();
        }
        catch (InterruptedException ignored) {}
        finally {
            obLock.unlock();
        }

And here is my code for signaling the condition

obLock.lock();
        try {
            while (dealerHand < dealer.getBreakpoint()) {
                drawCard(dealer);
                dealerHand = dealer.getHandValue();
            }
            dealerDone.signalAll();
        } finally { 
            obLock.unlock();
        }

Declaring my lock/Condition

private static Lock obLock = new ReentrantLock();
private static Condition dealerDone = obLock.newCondition();

I've tried turning it into a synchronized block (although we weren't taught about them in class so I'm not super familiar with them), but it gives me the same issue.

I've tried making 2 different locks so that they aren't both locked at the same time, but I think it has more to do with players interacting with each other than the dealer interacting with players.

0

There are 0 answers