Skip to content

Commit 0b9ea53

Browse files
chore(internal): add async lock helper
1 parent 984e85d commit 0b9ea53

File tree

1 file changed

+23
-0
lines changed
  • openai-java-core/src/main/kotlin/com/openai/core

1 file changed

+23
-0
lines changed

openai-java-core/src/main/kotlin/com/openai/core/Utils.kt

Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,8 @@ package com.openai.core
55
import com.openai.errors.OpenAIInvalidDataException
66
import java.util.Collections
77
import java.util.SortedMap
8+
import java.util.concurrent.CompletableFuture
9+
import java.util.concurrent.locks.Lock
810

911
@JvmSynthetic
1012
internal fun <T : Any> T?.getOrThrow(name: String): T =
@@ -101,3 +103,24 @@ internal fun isAzureEndpoint(baseUrl: String): Boolean {
101103
}
102104

103105
internal interface Enum
106+
107+
/**
108+
* Executes the given [action] while holding the lock, returning a [CompletableFuture] with the
109+
* result.
110+
*
111+
* @param action The asynchronous action to execute while holding the lock
112+
* @return A [CompletableFuture] that completes with the result of the action
113+
*/
114+
@JvmSynthetic
115+
internal fun <T> Lock.withLockAsync(action: () -> CompletableFuture<T>): CompletableFuture<T> {
116+
lock()
117+
val future =
118+
try {
119+
action()
120+
} catch (e: Throwable) {
121+
unlock()
122+
throw e
123+
}
124+
future.whenComplete { _, _ -> unlock() }
125+
return future
126+
}

0 commit comments

Comments
 (0)