Skip to content

Commit 290ee95

Browse files
chore(internal): add async lock helper
1 parent 9e577c2 commit 290ee95

File tree

1 file changed

+23
-0
lines changed
  • finch-java-core/src/main/kotlin/com/tryfinch/api/core

1 file changed

+23
-0
lines changed

finch-java-core/src/main/kotlin/com/tryfinch/api/core/Utils.kt

Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,8 @@ import com.tryfinch.api.core.http.Headers
66
import com.tryfinch.api.errors.FinchInvalidDataException
77
import java.util.Collections
88
import java.util.SortedMap
9+
import java.util.concurrent.CompletableFuture
10+
import java.util.concurrent.locks.Lock
911

1012
@JvmSynthetic
1113
internal fun <T : Any> T?.getOrThrow(name: String): T =
@@ -95,3 +97,24 @@ internal fun Headers.getRequiredHeader(name: String): String =
9597
values(name).firstOrNull() ?: throw FinchInvalidDataException("Could not find $name header")
9698

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

0 commit comments

Comments
 (0)