use of java.util.concurrent.CompletableFuture in project jodd by oblac.
the class Futures method failAfter.
/**
* Returns {@code CompletableFuture} that fails after certain number of milliseconds.
*/
public static <T> CompletableFuture<T> failAfter(long duration) {
final CompletableFuture<T> promise = new CompletableFuture<>();
SCHEDULER.schedule(() -> {
final TimeoutException ex = new TimeoutException("Timeout after " + duration);
return promise.completeExceptionally(ex);
}, duration, MILLISECONDS);
return promise;
}
use of java.util.concurrent.CompletableFuture in project pulsar by yahoo.
the class ManagedCursorConcurrencyTest method testCloseAndRead.
@Test
public void testCloseAndRead() throws Exception {
ManagedLedger ledger = factory.open("my_test_ledger_test_close_and_read", new ManagedLedgerConfig().setMaxEntriesPerLedger(2));
final ManagedCursor cursor = ledger.openCursor("c1");
final CompletableFuture<String> closeFuture = new CompletableFuture<>();
final String CLOSED = "closed";
final List<Position> addedEntries = Lists.newArrayList();
for (int i = 0; i < 1000; i++) {
Position pos = ledger.addEntry("entry".getBytes());
addedEntries.add(pos);
}
final CyclicBarrier barrier = new CyclicBarrier(2);
final CountDownLatch counter = new CountDownLatch(2);
final AtomicBoolean gotException = new AtomicBoolean(false);
Thread deleter = new Thread() {
public void run() {
try {
barrier.await();
for (Position position : addedEntries) {
cursor.markDelete(position);
Thread.sleep(1);
}
} catch (ManagedLedgerException e) {
if (!e.getMessage().equals("Cursor was already closed")) {
gotException.set(true);
}
} catch (Exception e) {
e.printStackTrace();
gotException.set(true);
} finally {
counter.countDown();
}
}
};
Thread reader = new Thread() {
public void run() {
try {
barrier.await();
for (int i = 0; i < 1000; i++) {
cursor.readEntries(1).forEach(e -> e.release());
// Thread.sleep(2,200);
Thread.sleep(2, 195);
}
cursor.asyncClose(new AsyncCallbacks.CloseCallback() {
@Override
public void closeComplete(Object ctx) {
log.info("Successfully closed cursor ledger");
closeFuture.complete(CLOSED);
}
@Override
public void closeFailed(ManagedLedgerException exception, Object ctx) {
log.error("Error closing cursor: ", exception);
closeFuture.completeExceptionally(new Exception(exception));
}
}, null);
} catch (Exception e) {
e.printStackTrace();
gotException.set(true);
} finally {
counter.countDown();
}
}
};
deleter.start();
reader.start();
counter.await();
assertEquals(gotException.get(), false);
assertEquals(closeFuture.get(), CLOSED);
}
use of java.util.concurrent.CompletableFuture in project pulsar by yahoo.
the class ManagedLedgerFactoryImpl method asyncOpen.
@Override
public void asyncOpen(final String name, final ManagedLedgerConfig config, final OpenLedgerCallback callback, final Object ctx) {
// If the ledger state is bad, remove it from the map.
CompletableFuture<ManagedLedgerImpl> existingFuture = ledgers.get(name);
if (existingFuture != null && existingFuture.isDone()) {
try {
ManagedLedgerImpl l = existingFuture.get();
if (l.getState().equals(State.Fenced.toString()) || l.getState().equals(State.Closed.toString())) {
// Managed ledger is in unusable state. Recreate it.
log.warn("[{}] Attempted to open ledger in {} state. Removing from the map to recreate it", name, l.getState());
ledgers.remove(name, existingFuture);
}
} catch (Exception e) {
// Unable to get the future
log.warn("[{}] Got exception while trying to retrieve ledger", name, e);
}
}
// Ensure only one managed ledger is created and initialized
ledgers.computeIfAbsent(name, (mlName) -> {
// Create the managed ledger
CompletableFuture<ManagedLedgerImpl> future = new CompletableFuture<>();
final ManagedLedgerImpl newledger = new ManagedLedgerImpl(this, bookKeeper, store, config, executor, orderedExecutor, name);
newledger.initialize(new ManagedLedgerInitializeLedgerCallback() {
@Override
public void initializeComplete() {
future.complete(newledger);
}
@Override
public void initializeFailed(ManagedLedgerException e) {
// Clean the map if initialization fails
ledgers.remove(name, future);
future.completeExceptionally(e);
}
}, null);
return future;
}).thenAccept(ml -> {
callback.openLedgerComplete(ml, ctx);
}).exceptionally(exception -> {
callback.openLedgerFailed((ManagedLedgerException) exception.getCause(), ctx);
return null;
});
}
use of java.util.concurrent.CompletableFuture in project pulsar by yahoo.
the class Futures method waitForAll.
public static CompletableFuture<Void> waitForAll(List<CompletableFuture<Void>> futures) {
final CompletableFuture<Void> compositeFuture = new CompletableFuture<>();
final AtomicInteger count = new AtomicInteger(futures.size());
for (CompletableFuture<Void> future : futures) {
future.whenComplete((r, ex) -> {
if (ex != null) {
compositeFuture.completeExceptionally(ex);
} else if (count.decrementAndGet() == 0) {
// All the pending futures did complete
compositeFuture.complete(null);
}
});
}
if (futures.isEmpty()) {
compositeFuture.complete(null);
}
return compositeFuture;
}
use of java.util.concurrent.CompletableFuture in project pulsar by yahoo.
the class PersistentTopic method unsubscribe.
/**
* Delete the cursor ledger for a given subscription
*
* @param subscriptionName
* Subscription for which the cursor ledger is to be deleted
* @return Completable future indicating completion of unsubscribe operation Completed exceptionally with:
* ManagedLedgerException if cursor ledger delete fails
*/
@Override
public CompletableFuture<Void> unsubscribe(String subscriptionName) {
CompletableFuture<Void> unsubscribeFuture = new CompletableFuture<>();
ledger.asyncDeleteCursor(Codec.encode(subscriptionName), new DeleteCursorCallback() {
@Override
public void deleteCursorComplete(Object ctx) {
if (log.isDebugEnabled()) {
log.debug("[{}][{}] Cursor deleted successfully", topic, subscriptionName);
}
subscriptions.remove(subscriptionName);
unsubscribeFuture.complete(null);
lastActive = System.nanoTime();
}
@Override
public void deleteCursorFailed(ManagedLedgerException exception, Object ctx) {
if (log.isDebugEnabled()) {
log.debug("[{}][{}] Error deleting cursor for subscription", topic, subscriptionName, exception);
}
unsubscribeFuture.completeExceptionally(new PersistenceException(exception));
}
}, null);
return unsubscribeFuture;
}
Aggregations