Diese Bibliothek enthält in einer JVM zwei APIs, eine für Java und eine für Kotlin. TicketBroker ist die Coroutine-basierte Kotlin-API, BlockingTicketBroker ist eine Java-freundliche, blockierende Fassade (basierend auf java.time.Duration), die ohne Coroutines auskommt. Intern kapseln beide denselben Broker.
val broker = TicketBroker.connect("127.0.0.1:5225")
broker.waitReady(5.seconds)
val ticket = broker.acquire("key", 5.seconds, 30.seconds)
ticket.release()
broker.close()Nebenläufigkeits-Beispiel (Ein-/Auszahlungen über je ein Konto-Lock gegenseitig ausgeschlossen):
suspend fun transaction(broker: TicketBroker, account: Int, delta: Long) {
val key = "account-$account"
val ticket = try {
broker.acquire(key, wait, lease)
} catch (e: Exception) {
log.error("account {} acquire failed: {}", account, e.message)
return
}
try {
val before = balances[account]
yield()
balances[account] = before + delta
} finally {
ticket.close() // Automatische Rückgabe im Hintergrund
}
val (action, sign) = if (delta < 0) "withdraw" to '-' else "deposit" to '+'
log.info("account $account $action $sign\$$AMOUNT -> \$${balances[account]}")
}try (BlockingTicketBroker broker = BlockingTicketBroker.connect(List.of("127.0.0.1:5225"))) {
broker.waitReady(Duration.ofSeconds(5));
BlockingTicket ticket = broker.acquire("key", Duration.ofSeconds(5), Duration.ofSeconds(30));
ticket.release();
System.out.println("pass");
}Nebenläufigkeits-Beispiel (Konto-Lock, gleichzeitige Ausführung in mehreren Threads über ExecutorService):
void transaction(BlockingTicketBroker broker, int account, long delta) {
String key = "account-" + account;
try (BlockingTicket ticket = broker.acquire(key, WAIT, LEASE)) {
long before = balances[account];
Thread.yield();
balances[account] = before + delta;
}
String action = delta < 0 ? "withdraw" : "deposit";
char sign = delta < 0 ? '-' : '+';
log.info("account {} {} {}${} -> ${}", account, action, sign, AMOUNT, balances[account]);
}Das vollständige Beispiel finden Sie in ExampleSimpleTest.kt / ExampleBankTest.kt (Kotlin), ExampleSimpleJavaTest.java / ExampleBankJavaTest.java (Java).