Skip to content

Commit

Permalink
Fix some lock issues (#2339)
Browse files Browse the repository at this point in the history
  • Loading branch information
MinnDevelopment committed Nov 27, 2022
1 parent b3479a1 commit e28f7be
Show file tree
Hide file tree
Showing 3 changed files with 16 additions and 31 deletions.
10 changes: 4 additions & 6 deletions src/main/java/net/dv8tion/jda/api/utils/MiscUtil.java
Original file line number Diff line number Diff line change
Expand Up @@ -126,29 +126,27 @@ public static long parseSnowflake(String input)

public static <E> E locked(ReentrantLock lock, Supplier<E> task)
{
tryLock(lock);
try
{
tryLock(lock);
return task.get();
}
finally
{
if (lock.isHeldByCurrentThread())
lock.unlock();
lock.unlock();
}
}

public static void locked(ReentrantLock lock, Runnable task)
{
tryLock(lock);
try
{
tryLock(lock);
task.run();
}
finally
{
if (lock.isHeldByCurrentThread())
lock.unlock();
lock.unlock();
}
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -1107,47 +1107,29 @@ public void onThreadCreated(WebSocket websocket, ThreadType threadType, Thread t
}
}

protected void maybeUnlock()
{
if (queueLock.isHeldByCurrentThread())
queueLock.unlock();
}

protected void locked(String comment, Runnable task)
{
try
{
if (!queueLock.tryLock() && !queueLock.tryLock(10, TimeUnit.SECONDS))
throw new IllegalStateException("Could not acquire lock in reasonable timeframe! (10 seconds)");
task.run();
MiscUtil.locked(queueLock, task);
}
catch (InterruptedException e)
catch (Exception e)
{
LOG.error(comment, e);
}
finally
{
maybeUnlock();
}
}

protected <T> T locked(String comment, Supplier<T> task)
{
try
{
if (!queueLock.tryLock() && !queueLock.tryLock(10, TimeUnit.SECONDS))
throw new IllegalStateException("Could not acquire lock in reasonable timeframe! (10 seconds)");
return task.get();
return MiscUtil.locked(queueLock, task);
}
catch (InterruptedException e)
catch (Exception e)
{
LOG.error(comment, e);
return null;
}
finally
{
maybeUnlock();
}
}

public void queueAudioReconnect(AudioChannel channel)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -109,14 +109,19 @@ public void run()

ConnectionRequest audioRequest = null;
DataObject chunkRequest = null;

boolean hasLock = false;

try
{
api.setContext();
attemptedToSend = false;
needRateLimit = false;
// We do this outside of the lock because otherwise we could potentially deadlock here
audioRequest = client.getNextAudioConnectRequest();
if (!queueLock.tryLock() && !queueLock.tryLock(10, TimeUnit.SECONDS))

hasLock = queueLock.tryLock() || queueLock.tryLock(10, TimeUnit.SECONDS);
if (!hasLock)
{
scheduleNext();
return;
Expand Down Expand Up @@ -155,8 +160,8 @@ else if (audioRequest != null)
}
finally
{
// on any exception that might cause this lock to not release
client.maybeUnlock();
if (hasLock)
queueLock.unlock();
}

scheduleNext();
Expand Down

0 comments on commit e28f7be

Please sign in to comment.