Java Code Examples for org.redisson.api.RFuture#cancel()
The following examples show how to use
org.redisson.api.RFuture#cancel() .
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: RedissonBoundedBlockingQueue.java From redisson with Apache License 2.0 | 6 votes |
private RPromise<V> wrapTakeFuture(RFuture<V> takeFuture) { RPromise<V> result = new RedissonPromise<V>() { @Override public boolean cancel(boolean mayInterruptIfRunning) { super.cancel(mayInterruptIfRunning); return takeFuture.cancel(mayInterruptIfRunning); }; }; takeFuture.onComplete((res, e) -> { if (e != null) { result.tryFailure(e); return; } if (res == null) { result.trySuccess(takeFuture.getNow()); return; } createSemaphore(null).releaseAsync().onComplete((r, ex) -> { result.trySuccess(takeFuture.getNow()); }); }); return result; }
Example 2
Source File: TasksRunnerService.java From redisson with Apache License 2.0 | 6 votes |
@Override public void schedule(ScheduledCronExpressionParameters params) { CronExpression expression = new CronExpression(params.getCronExpression()); expression.setTimeZone(TimeZone.getTimeZone(params.getTimezone())); Date nextStartDate = expression.getNextValidTimeAfter(new Date()); RFuture<Void> future = null; if (nextStartDate != null) { RemoteExecutorServiceAsync service = asyncScheduledServiceAtFixed(params.getExecutorId(), params.getRequestId()); params.setStartTime(nextStartDate.getTime()); future = service.schedule(params); } try { executeRunnable(params, nextStartDate == null); } catch (Exception e) { // cancel task if it throws an exception if (future != null) { future.cancel(true); } throw e; } }
Example 3
Source File: RedissonBlockingQueueTest.java From redisson with Apache License 2.0 | 6 votes |
@Test public void testTakeAsyncCancel() { Config config = createConfig(); config.useSingleServer().setConnectionMinimumIdleSize(1).setConnectionPoolSize(1); RedissonClient redisson = Redisson.create(config); RBlockingQueue<Integer> queue1 = getQueue(redisson); for (int i = 0; i < 10; i++) { RFuture<Integer> f = queue1.takeAsync(); f.cancel(true); } assertThat(queue1.add(1)).isTrue(); assertThat(queue1.add(2)).isTrue(); assertThat(queue1.size()).isEqualTo(2); redisson.shutdown(); }
Example 4
Source File: RedissonBlockingQueueTest.java From redisson with Apache License 2.0 | 6 votes |
@Test public void testPollAsyncCancel() { Config config = createConfig(); config.useSingleServer().setConnectionMinimumIdleSize(1).setConnectionPoolSize(1); RedissonClient redisson = Redisson.create(config); RBlockingQueue<Integer> queue1 = getQueue(redisson); for (int i = 0; i < 10; i++) { RFuture<Integer> f = queue1.pollAsync(1, TimeUnit.SECONDS); f.cancel(true); } assertThat(queue1.add(1)).isTrue(); assertThat(queue1.add(2)).isTrue(); assertThat(queue1.size()).isEqualTo(2); redisson.shutdown(); }
Example 5
Source File: RedissonBoundedBlockingQueueTest.java From redisson with Apache License 2.0 | 6 votes |
@Test public void testTakeAsyncCancel() { Config config = createConfig(); config.useSingleServer().setConnectionMinimumIdleSize(1).setConnectionPoolSize(1); RedissonClient redisson = Redisson.create(config); redisson.getKeys().flushall(); RBoundedBlockingQueue<Integer> queue1 = redisson.getBoundedBlockingQueue("testTakeAsyncCancel"); assertThat(queue1.trySetCapacity(15)).isTrue(); for (int i = 0; i < 10; i++) { RFuture<Integer> f = queue1.takeAsync(); f.cancel(true); } assertThat(queue1.add(1)).isTrue(); assertThat(queue1.add(2)).isTrue(); assertThat(queue1.size()).isEqualTo(2); redisson.shutdown(); }
Example 6
Source File: RedissonBoundedBlockingQueueTest.java From redisson with Apache License 2.0 | 6 votes |
@Test public void testPollAsyncCancel() { Config config = createConfig(); config.useSingleServer().setConnectionMinimumIdleSize(1).setConnectionPoolSize(1); RedissonClient redisson = Redisson.create(config); redisson.getKeys().flushall(); RBoundedBlockingQueue<Integer> queue1 = redisson.getBoundedBlockingQueue("queue:pollany"); assertThat(queue1.trySetCapacity(15)).isTrue(); for (int i = 0; i < 10; i++) { RFuture<Integer> f = queue1.pollAsync(1, TimeUnit.SECONDS); f.cancel(true); } assertThat(queue1.add(1)).isTrue(); assertThat(queue1.add(2)).isTrue(); assertThat(queue1.size()).isEqualTo(2); redisson.shutdown(); }
Example 7
Source File: ElementsSubscribeService.java From redisson with Apache License 2.0 | 5 votes |
public void unsubscribe(int listenerId) { RFuture<?> f; synchronized (subscribeListeners) { f = subscribeListeners.remove(listenerId); } if (f != null) { f.cancel(false); } }
Example 8
Source File: TasksRunnerService.java From redisson with Apache License 2.0 | 5 votes |
@Override public void scheduleAtFixedRate(ScheduledAtFixedRateParameters params) { long newStartTime = System.currentTimeMillis() + params.getPeriod(); params.setStartTime(newStartTime); RFuture<Void> future = asyncScheduledServiceAtFixed(params.getExecutorId(), params.getRequestId()).scheduleAtFixedRate(params); try { executeRunnable(params); } catch (Exception e) { // cancel task if it throws an exception future.cancel(true); throw e; } }
Example 9
Source File: RedissonMapReduceTest.java From redisson with Apache License 2.0 | 5 votes |
@Test public void testCancel() throws InterruptedException, ExecutionException { RMap<String, String> map = getMap(); for (int i = 0; i < 100000; i++) { map.put("" + i, "ab cd fjks"); } RMapReduce<String, String, String, Integer> mapReduce = map.<String, Integer>mapReduce().mapper(new WordMapper()).reducer(new WordReducer()); RFuture<Map<String, Integer>> future = mapReduce.executeAsync(); Thread.sleep(100); future.cancel(true); }
Example 10
Source File: CoordinatorTask.java From redisson with Apache License 2.0 | 4 votes |
@Override public Object call() throws Exception { long timeSpent = System.currentTimeMillis() - startTime; if (isTimeoutExpired(timeSpent)) { throw new MapReduceTimeoutException(); } this.codec = (Codec) objectCodecClass.getConstructor().newInstance(); RScheduledExecutorService executor = redisson.getExecutorService(RExecutorService.MAPREDUCE_NAME); int workersAmount = executor.countActiveWorkers(); UUID id = UUID.randomUUID(); String collectorMapName = objectName + ":collector:" + id; mapperTask.setCollectorMapName(collectorMapName); mapperTask.setWorkersAmount(workersAmount); timeSpent = System.currentTimeMillis() - startTime; if (isTimeoutExpired(timeSpent)) { throw new MapReduceTimeoutException(); } if (timeout > 0) { mapperTask.setTimeout(timeout - timeSpent); } mapperTask.addObjectName(objectName); RFuture<?> mapperFuture = executor.submitAsync(mapperTask); try { if (timeout > 0 && !mapperFuture.await(timeout - timeSpent)) { mapperFuture.cancel(true); throw new MapReduceTimeoutException(); } if (timeout == 0) { mapperFuture.await(); } } catch (InterruptedException e) { mapperFuture.cancel(true); return null; } SubTasksExecutor reduceExecutor = new SubTasksExecutor(executor, workersAmount, startTime, timeout); for (int i = 0; i < workersAmount; i++) { String name = collectorMapName + ":" + i; Runnable runnable = new ReducerTask<KOut, VOut>(name, reducer, objectCodecClass, resultMapName, timeout - timeSpent); reduceExecutor.submit(runnable); } if (!reduceExecutor.await()) { return null; } return executeCollator(); }
Example 11
Source File: SubTasksExecutor.java From redisson with Apache License 2.0 | 4 votes |
private void cancel(List<RFuture<?>> futures) { for (RFuture<?> future : futures) { future.cancel(true); } }
Example 12
Source File: RedisExecutor.java From redisson with Apache License 2.0 | 4 votes |
public void execute() { if (mainPromise.isCancelled()) { free(); return; } if (!connectionManager.getShutdownLatch().acquire()) { free(); mainPromise.tryFailure(new RedissonShutdownException("Redisson is shutdown")); return; } codec = getCodec(codec); RFuture<RedisConnection> connectionFuture = getConnection(); RPromise<R> attemptPromise = new RedissonPromise<R>(); mainPromiseListener = (r, e) -> { if (mainPromise.isCancelled() && connectionFuture.cancel(false)) { log.debug("Connection obtaining canceled for {}", command); timeout.cancel(); if (attemptPromise.cancel(false)) { free(); } } }; if (attempt == 0) { mainPromise.onComplete((r, e) -> { if (this.mainPromiseListener != null) { this.mainPromiseListener.accept(r, e); } }); } scheduleRetryTimeout(connectionFuture, attemptPromise); connectionFuture.onComplete((connection, e) -> { if (connectionFuture.isCancelled()) { connectionManager.getShutdownLatch().release(); return; } if (!connectionFuture.isSuccess()) { connectionManager.getShutdownLatch().release(); exception = convertException(connectionFuture); return; } sendCommand(attemptPromise, connection); writeFuture.addListener(new ChannelFutureListener() { @Override public void operationComplete(ChannelFuture future) throws Exception { checkWriteFuture(writeFuture, attemptPromise, connection); } }); releaseConnection(attemptPromise, connectionFuture); }); attemptPromise.onComplete((r, e) -> { checkAttemptPromise(attemptPromise, connectionFuture); }); }
Example 13
Source File: RedisExecutor.java From redisson with Apache License 2.0 | 4 votes |
private void scheduleRetryTimeout(RFuture<RedisConnection> connectionFuture, RPromise<R> attemptPromise) { TimerTask retryTimerTask = new TimerTask() { @Override public void run(Timeout t) throws Exception { if (attemptPromise.isDone()) { return; } if (connectionFuture.cancel(false)) { if (exception == null) { exception = new RedisTimeoutException("Unable to acquire connection! Increase connection pool size and/or retryInterval settings " + "Node source: " + source + ", command: " + LogHelper.toString(command, params) + " after " + attempt + " retry attempts"); } } else { if (connectionFuture.isSuccess()) { if (writeFuture == null || !writeFuture.isDone()) { if (attempt == attempts) { if (writeFuture != null && writeFuture.cancel(false)) { if (exception == null) { long totalSize = 0; if (params != null) { for (Object param : params) { if (param instanceof ByteBuf) { totalSize += ((ByteBuf) param).readableBytes(); } } } exception = new RedisTimeoutException("Command still hasn't been written into connection! Increase nettyThreads and/or retryInterval settings. Payload size in bytes: " + totalSize + ". Node source: " + source + ", connection: " + connectionFuture.getNow() + ", command: " + LogHelper.toString(command, params) + " after " + attempt + " retry attempts"); } attemptPromise.tryFailure(exception); } return; } attempt++; scheduleRetryTimeout(connectionFuture, attemptPromise); return; } if (writeFuture.isSuccess()) { return; } } } if (mainPromise.isCancelled()) { if (attemptPromise.cancel(false)) { free(); } return; } if (attempt == attempts) { // filled out in connectionFuture or writeFuture handler attemptPromise.tryFailure(exception); return; } if (!attemptPromise.cancel(false)) { return; } attempt++; if (log.isDebugEnabled()) { log.debug("attempt {} for command {} and params {}", attempt, command, LogHelper.toString(params)); } mainPromiseListener = null; execute(); } }; timeout = connectionManager.newTimeout(retryTimerTask, retryInterval, TimeUnit.MILLISECONDS); }
Example 14
Source File: RedissonLock.java From redisson with Apache License 2.0 | 4 votes |
@Override public boolean tryLock(long waitTime, long leaseTime, TimeUnit unit) throws InterruptedException { long time = unit.toMillis(waitTime); long current = System.currentTimeMillis(); long threadId = Thread.currentThread().getId(); Long ttl = tryAcquire(leaseTime, unit, threadId); // lock acquired if (ttl == null) { return true; } time -= System.currentTimeMillis() - current; if (time <= 0) { acquireFailed(threadId); return false; } current = System.currentTimeMillis(); RFuture<RedissonLockEntry> subscribeFuture = subscribe(threadId); if (!subscribeFuture.await(time, TimeUnit.MILLISECONDS)) { if (!subscribeFuture.cancel(false)) { subscribeFuture.onComplete((res, e) -> { if (e == null) { unsubscribe(subscribeFuture, threadId); } }); } acquireFailed(threadId); return false; } try { time -= System.currentTimeMillis() - current; if (time <= 0) { acquireFailed(threadId); return false; } while (true) { long currentTime = System.currentTimeMillis(); ttl = tryAcquire(leaseTime, unit, threadId); // lock acquired if (ttl == null) { return true; } time -= System.currentTimeMillis() - currentTime; if (time <= 0) { acquireFailed(threadId); return false; } // waiting for message currentTime = System.currentTimeMillis(); if (ttl >= 0 && ttl < time) { subscribeFuture.getNow().getLatch().tryAcquire(ttl, TimeUnit.MILLISECONDS); } else { subscribeFuture.getNow().getLatch().tryAcquire(time, TimeUnit.MILLISECONDS); } time -= System.currentTimeMillis() - currentTime; if (time <= 0) { acquireFailed(threadId); return false; } } } finally { unsubscribe(subscribeFuture, threadId); } // return get(tryLockAsync(waitTime, leaseTime, unit)); }