Java Code Examples for java.util.concurrent.Future.get()

The following are Jave code examples for showing how to use get() of the java.util.concurrent.Future class. You can vote up the examples you like. Your votes will be used in our system to get more good examples.
+ Save this method
Example 1
Project: fresco_floodlight   File: StorageTest.java   View Source Code Vote up 6 votes
@Test
public void testAsyncQuery2() {
    Object[][] expectedResults = {
            {"John", "Smith", 40},
            {"Jim", "White", 24},
    };
    String[] columnList = {PERSON_FIRST_NAME,PERSON_LAST_NAME,PERSON_AGE};
    IPredicate predicate = new OperatorPredicate(PERSON_LAST_NAME, OperatorPredicate.Operator.GTE, "Sm");
    Future<IResultSet> future = storageSource.executeQueryAsync(PERSON_TABLE_NAME,
            columnList, predicate, new RowOrdering(PERSON_SSN));
    waitForFuture(future);
    try {
        IResultSet resultSet = future.get();
        checkExpectedResults(resultSet, columnList, expectedResults);
    }
    catch (Exception e) {
        fail("Exception thrown in async storage operation: " + e.toString());
    }
}
 
Example 2
Project: cruise-control   File: GoalOptimizer.java   View Source Code Vote up 6 votes
private void computeBestProposal() {
  long start = _time.milliseconds();
  List<Future> futures = new ArrayList<>();
  for (int i = 0; i < _numPrecomputingThreads; i++) {
    futures.add(_proposalPrecomputingExecutor.submit(new ProposalCandidateComputer(_goalByPriorityForPrecomputing.get(i))));
  }
  for (Future future : futures) {
    try {
      boolean done = false;
      while (!_shutdown && !done) {
        try {
          future.get();
          done = true;
        } catch (InterruptedException ie) {
          LOG.debug("Goal optimizer received exception when precomputing the proposal candidates {}.", ie.toString());
        }
      }
    } catch (ExecutionException ee) {
      LOG.error("Goal optimizer received exception when precomputing the proposal candidates.", ee);
    }
  }
  LOG.info("Finished precomputation {} proposal candidates in {} ms", _totalProposalCandidateComputed.get() - 1,
           _time.milliseconds() - start);
}
 
Example 3
Project: neoscada   File: Authenticator.java   View Source Code Vote up 6 votes
@Override
protected void handleComplete ( final Future<UserInformation> future, final ConfigurationGroup group ) throws Exception
{
    logger.debug ( "Handle complete - future: {}, group: {}", future, group );

    final UserInformation userInformation = future.get ();
    if ( userInformation != null )
    {
        setResult ( userInformation );
    }
    else
    {
        if ( this.counter < group.getRetries () )
        {
            logger.debug ( "Retry current group - retry #{} of {}", this.counter, group.getRetries () );
            this.counter++;
            processCurrent ();
        }
        else
        {
            logger.debug ( "Try next authorization group" );
            this.counter = 1;
            processNext ();
        }
    }
}
 
Example 4
Project: opendaylight   File: HelloIT.java   View Source Code Vote up 6 votes
@Test
public void testRPC() throws InterruptedException, ExecutionException {
    String name = "Ed Warnicke";
    HelloService service = getSession().getRpcService(HelloService.class);

    HelloWorldInput input = new HelloWorldInputBuilder()
            .setName(name)
            .build();
    Future<RpcResult<HelloWorldOutput>> outputFuture = service.helloWorld(input);
    RpcResult<HelloWorldOutput> outputResult = outputFuture.get();
    Assert.assertTrue("RPC was unsuccessful", outputResult.isSuccessful());
    Assert.assertEquals("Did not receive the expected response to helloWorld RPC", "Hello " + name,
            outputResult.getResult().getGreeting());

    validateRPCResponse(name, outputResult.getResult().getGreeting());
    validateGreetingRegistry(name);
}
 
Example 5
Project: de.flapdoodle.solid   File: PathWatcherTest.java   View Source Code Vote up 5 votes
@Test
@Ignore
public void watcherMustNotify() throws InterruptedException, ExecutionException {
	File tempDir = Files.createTempDir();
	
	AtomicBoolean shouldCreateFiles = new AtomicBoolean(true);
	AtomicInteger changeCounter=new AtomicInteger(0);
	
	Future<?> fileChanger = Executors.newSingleThreadExecutor().submit(() -> {
		int i=0;
		while (shouldCreateFiles.get()) {
			int run=i++;
			
			Try.runable(() -> {
					System.out.println("run "+run);
					System.out.flush();
					java.nio.file.Files.write(tempDir.toPath().resolve("test"+run), "".getBytes(Charsets.UTF_8), StandardOpenOption.CREATE_NEW);
					java.nio.file.Files.write(tempDir.toPath().resolve("test"+run+"b"), "".getBytes(Charsets.UTF_8), StandardOpenOption.CREATE_NEW);
					Thread.sleep(100);
				})
				.mapCheckedException(RuntimeException::new)
				.run();
		}
	});
	
	PathWatcher.watch(tempDir.toPath())
	.every(1, TimeUnit.SECONDS)
	.with(changes -> {
				return changeCounter.addAndGet(changes.size()) > 10;
			});
	
	shouldCreateFiles.set(false);
	fileChanger.get();
	
	System.out.println("DONE");
	System.out.flush();
}
 
Example 6
Project: scanning   File: LevelRunner.java   View Source Code Vote up 5 votes
private IPosition getPosition(IPosition position, List<Future<IPosition>> futures) throws InterruptedException, ExecutionException {
	MapPosition ret = new MapPosition();
    for (Future<IPosition> future : futures) {
	// Faster than using composite
	IPosition pos = future.get();
	if (pos==null) continue;
	ret.putAll(pos);
	ret.putAllIndices(pos);
	}
    if (ret.size()<1) return position;
    return ret;
}
 
Example 7
Project: NEILREN4J   File: MemcachedManager.java   View Source Code Vote up 5 votes
/**
 * 从缓存中获取.
 *
 * @param keys keys
 * @return Map<String, Object>
 */
public Map<String, Object> asyncGetMulti(Collection<String> keys) {
    Map<String, Object> map = null;
    Future<Map<String, Object>> f = memcachedClient.asyncGetBulk(keys);
    try {
        map = f.get(SpyMemcachedConstants.DEFAULT_TIMEOUT, SpyMemcachedConstants.DEFAULT_TIMEUNIT);
    } catch (Exception e) {
        f.cancel(false);
    }
    return map;
}
 
Example 8
Project: mDL-ILP   File: WebAPI.java   View Source Code Vote up 5 votes
@Override
protected MobileDrivingLicense doInBackground(Void... voids) {

    Callable<MobileDrivingLicense> registerTask = new WebAPI.DownloadLicenseTask();
    Future<MobileDrivingLicense> f = service.submit(registerTask);

    MobileDrivingLicense license = null;
    try {
        license = f.get();
    } catch (InterruptedException | ExecutionException e) {
        Log.e(getClass().getName(), e.getMessage(), e);
    }

    return license;
}
 
Example 9
Project: NEILREN4J   File: MemcachedManager.java   View Source Code Vote up 5 votes
private boolean getBooleanValue(Future<Boolean> f) {
    try {
        Boolean bool = f.get(SpyMemcachedConstants.DEFAULT_TIMEOUT, SpyMemcachedConstants.DEFAULT_TIMEUNIT);
        return bool.booleanValue();
    } catch (Exception e) {
        f.cancel(false);
        return false;
    }
}
 
Example 10
Project: NEILREN4J   File: MemcachedManager.java   View Source Code Vote up 5 votes
/**
 * 从缓存中获取.
 *
 * @param key key
 * @return Object
 */
public Object asyncGet(String key) {
    Object obj = null;
    Future<Object> f = memcachedClient.asyncGet(key);
    try {
        obj = f.get(SpyMemcachedConstants.DEFAULT_TIMEOUT, SpyMemcachedConstants.DEFAULT_TIMEUNIT);
    } catch (Exception e) {
        f.cancel(false);
    }
    return obj;
}
 
Example 11
Project: OperatieBRP   File: PersoonCacheProducer.java   View Source Code Vote up 4 votes
private void wachtTotKlaar(List<Future<Object>> futures)
        throws InterruptedException, ExecutionException, TimeoutException {
    for (Future<Object> future : futures) {
        future.get(1, TimeUnit.MINUTES);
    }
}
 
Example 12
Project: incubator-netbeans   File: RequestProcessor180386Test.java   View Source Code Vote up 4 votes
@RandomlyFails // NB-Core-Build #8322: hung
    public void testScheduleRepeatingIntervalsAreRoughlyCorrect() throws Exception {
        int runCount = 5;
        final CountDownLatch latch = new CountDownLatch(runCount);
        final List<Long> intervals = Collections.synchronizedList(new ArrayList<Long> (runCount));
//        long initialDelay = 30000;
//        long period = 20000;
//        long fudgeFactor = 4000;
        long initialDelay = 3000;
        long period = 2000;
        long fudgeFactor = 400;
        long expectedInitialDelay = initialDelay - fudgeFactor;
        long expectedPeriod = period - fudgeFactor;
        class C implements Runnable {
            volatile long start = System.currentTimeMillis();
            private int runCount;
            @Override
            public void run() {
                runCount++;
                try {
                    synchronized(this) {
                        long end = System.currentTimeMillis();
                        intervals.add (end - start);
                        start = end;
                    }
                } finally {
                    latch.countDown();
                }
            }
        }
        C c = new C();
        RequestProcessor rp = new RequestProcessor ("testScheduleRepeating", 5, true);
        try {
            Future<?> f = rp.scheduleWithFixedDelay(c, initialDelay, period, TimeUnit.MILLISECONDS);
    //        latch.await(initialDelay + fudgeFactor + ((runCount - 1) * (period + fudgeFactor)), TimeUnit.MILLISECONDS); //XXX
            latch.await();
            f.cancel(true);
            for (int i= 0; i < Math.min(runCount, intervals.size()); i++) {
                long expect = i == 0 ? expectedInitialDelay : expectedPeriod;
                assertTrue ("Expected at least " + expect + " milliseconds before run " + i + " but was " + intervals.get(i), intervals.get(i) >= expect);
            }
            //Ensure we have really exited
            try {
                f.get();
                fail ("CancellationException should have been thrown");
            } catch (CancellationException e) {}
            assertTrue(f.isCancelled());
            assertTrue(f.isDone());
        } finally {
            rp.stop();
        }
    }
 
Example 13
Project: hadoop   File: TestSaveNamespace.java   View Source Code Vote up 4 votes
@Test(timeout=20000)
public void testCancelSaveNamespace() throws Exception {
  Configuration conf = getConf();
  NameNode.initMetrics(conf, NamenodeRole.NAMENODE);
  DFSTestUtil.formatNameNode(conf);
  FSNamesystem fsn = FSNamesystem.loadFromDisk(conf);

  // Replace the FSImage with a spy
  final FSImage image = fsn.getFSImage();
  NNStorage storage = image.getStorage();
  storage.close(); // unlock any directories that FSNamesystem's initialization may have locked
  storage.setStorageDirectories(
      FSNamesystem.getNamespaceDirs(conf), 
      FSNamesystem.getNamespaceEditsDirs(conf));

  FSNamesystem spyFsn = spy(fsn);
  final FSNamesystem finalFsn = spyFsn;
  DelayAnswer delayer = new GenericTestUtils.DelayAnswer(LOG);
  BlockIdManager bid = spy(spyFsn.getBlockIdManager());
  Whitebox.setInternalState(finalFsn, "blockIdManager", bid);
  doAnswer(delayer).when(bid).getGenerationStampV2();

  ExecutorService pool = Executors.newFixedThreadPool(2);
  
  try {
    doAnEdit(fsn, 1);
    final Canceler canceler = new Canceler();
    
    // Save namespace
    fsn.setSafeMode(SafeModeAction.SAFEMODE_ENTER);
    try {
      Future<Void> saverFuture = pool.submit(new Callable<Void>() {
        @Override
        public Void call() throws Exception {
          image.saveNamespace(finalFsn, NameNodeFile.IMAGE, canceler);
          return null;
        }
      });

      // Wait until saveNamespace calls getGenerationStamp
      delayer.waitForCall();
      // then cancel the saveNamespace
      Future<Void> cancelFuture = pool.submit(new Callable<Void>() {
        @Override
        public Void call() throws Exception {
          canceler.cancel("cancelled");
          return null;
        }
      });
      // give the cancel call time to run
      Thread.sleep(500);
      
      // allow saveNamespace to proceed - it should check the cancel flag after
      // this point and throw an exception
      delayer.proceed();

      cancelFuture.get();
      saverFuture.get();
      fail("saveNamespace did not fail even though cancelled!");
    } catch (Throwable t) {
      GenericTestUtils.assertExceptionContains(
          "SaveNamespaceCancelledException", t);
    }
    LOG.info("Successfully cancelled a saveNamespace");


    // Check that we have only the original image and not any
    // cruft left over from half-finished images
    FSImageTestUtil.logStorageContents(LOG, storage);
    for (StorageDirectory sd : storage.dirIterable(null)) {
      File curDir = sd.getCurrentDir();
      GenericTestUtils.assertGlobEquals(curDir, "fsimage_.*",
          NNStorage.getImageFileName(0),
          NNStorage.getImageFileName(0) + MD5FileUtils.MD5_SUFFIX);
    }      
  } finally {
    fsn.close();
  }
}
 
Example 14
Project: incubator-netbeans   File: CslTestBase.java   View Source Code Vote up 4 votes
protected void checkSemantic(final String relFilePath, final String caretLine) throws Exception {
    Source testSource = getTestSource(getTestFile(relFilePath));

    if (caretLine != null) {
        int caretOffset = getCaretOffset(testSource.createSnapshot().getText().toString(), caretLine);
        enforceCaretOffset(testSource, caretOffset);
    }

    UserTask task = new UserTask() {
        public @Override void run(ResultIterator resultIterator) throws Exception {
            Parser.Result r = resultIterator.getParserResult();
            assertTrue(r instanceof ParserResult);
            ParserResult pr = (ParserResult) r;

            SemanticAnalyzer analyzer = getSemanticAnalyzer();
            assertNotNull("getSemanticAnalyzer must be implemented", analyzer);

            analyzer.run(pr, null);
            Map<OffsetRange, Set<ColoringAttributes>> highlights = analyzer.getHighlights();

            if (highlights == null) {
                highlights = Collections.emptyMap();
            }

            Document doc = GsfUtilities.getDocument(pr.getSnapshot().getSource().getFileObject(), true);
            checkNoOverlaps(highlights.keySet(), doc);

            String annotatedSource = annotateSemanticResults(doc, highlights);
            assertDescriptionMatches(relFilePath, annotatedSource, false, ".semantic");
        }
    };

    if (classPathsForTest == null || classPathsForTest.isEmpty()) {
        ParserManager.parse(Collections.singleton(testSource), task);
    } else {
        Future<Void> future = ParserManager.parseWhenScanFinished(Collections.singleton(testSource), task);
        if (!future.isDone()) {
            future.get();
        }
    }

}
 
Example 15
Project: tomcat7   File: TestWsWebSocketContainer.java   View Source Code Vote up 4 votes
private void doTestWriteTimeoutClient(boolean setTimeoutOnContainer)
        throws Exception {

    Tomcat tomcat = getTomcatInstance();
    // No file system docBase required
    Context ctx = tomcat.addContext("", null);
    ctx.addApplicationListener(BlockingConfig.class.getName());
    Tomcat.addServlet(ctx, "default", new DefaultServlet());
    ctx.addServletMapping("/", "default");

    WebSocketContainer wsContainer =
            ContainerProvider.getWebSocketContainer();

    // Set the async timeout
    if (setTimeoutOnContainer) {
        wsContainer.setAsyncSendTimeout(TIMEOUT_MS);
    }

    tomcat.start();

    Session wsSession = wsContainer.connectToServer(
            TesterProgrammaticEndpoint.class,
            ClientEndpointConfig.Builder.create().build(),
            new URI("ws://" + getHostName() + ":" + getPort() + BlockingConfig.PATH));

    if (!setTimeoutOnContainer) {
        wsSession.getAsyncRemote().setSendTimeout(TIMEOUT_MS);
    }

    long lastSend = 0;

    // Should send quickly until the network buffers fill up and then block
    // until the timeout kicks in
    Exception exception = null;
    try {
        while (true) {
            lastSend = System.currentTimeMillis();
            Future<Void> f = wsSession.getAsyncRemote().sendBinary(
                    ByteBuffer.wrap(MESSAGE_BINARY_4K));
            f.get();
        }
    } catch (Exception e) {
        exception = e;
    }

    long timeout = System.currentTimeMillis() - lastSend;

    // Clear the server side block and prevent further blocks to allow the
    // server to shutdown cleanly
    BlockingPojo.clearBlock();

    // Close the client session, primarily to allow the
    // BackgroundProcessManager to shut down.
    wsSession.close();

    String msg = "Time out was [" + timeout + "] ms";

    // Check correct time passed
    Assert.assertTrue(msg, timeout >= TIMEOUT_MS - MARGIN );

    // Check the timeout wasn't too long
    Assert.assertTrue(msg, timeout < TIMEOUT_MS * 2);

    Assert.assertNotNull(exception);
}
 
Example 16
Project: incubator-netbeans   File: RequestProcessor180386Test.java   View Source Code Vote up 4 votes
@RandomlyFails
    public void testScheduleFixedRateAreRoughlyCorrect() throws Exception {
        if (!TaskTest.canWait1s()) {
            LOG.warning("Skipping testWaitWithTimeOutReturnsAfterTimeOutWhenTheTaskIsNotComputedAtAll, as the computer is not able to wait 1s!");
            return;
        }
        int runCount = 5;
        final CountDownLatch latch = new CountDownLatch(runCount);
        final List<Long> intervals = Collections.synchronizedList(new ArrayList<Long> (runCount));
//        long initialDelay = 30000;
//        long period = 20000;
//        long fudgeFactor = 4000;
        long initialDelay = 3000;
        long period = 2000;
        long fudgeFactor = 400;
        long expectedInitialDelay = initialDelay - fudgeFactor;
        long expectedPeriod = period - fudgeFactor;
        class C implements Runnable {
            volatile long start = System.currentTimeMillis();
            private int runCount;
            @Override
            public void run() {
                runCount++;
                try {
                    synchronized(this) {
                        long end = System.currentTimeMillis();
                        intervals.add (end - start);
                        start = end;
                    }
                } finally {
                    latch.countDown();
                }
            }
        }
        C c = new C();
        RequestProcessor rp = new RequestProcessor ("testScheduleFixedRateAreRoughlyCorrect", 5, true);
        try {
            Future<?> f = rp.scheduleAtFixedRate(c, initialDelay, period, TimeUnit.MILLISECONDS);
            latch.await();
            f.cancel(true);
            StringBuilder failures = new StringBuilder();
            failures.append("Expected at least ").append(expectedInitialDelay).
                append(" milliseconds before run:\n");
            boolean fail = false;
            for (int i= 0; i < Math.min(runCount, intervals.size()); i++) {
                long expect = i == 0 ? expectedInitialDelay : expectedPeriod;
                failures.append("Round ").append(i).
                    append(" expected delay ").append(expect).
                    append(" but was ").append(intervals.get(i)).
                    append("\n");
                if (intervals.get(i) < expect) {
                    fail = true;
                }
            }
            if (fail) {
                fail(failures.toString());
            }
            //Ensure we have really exited
            try {
                f.get();
                fail ("CancellationException should have been thrown");
            } catch (CancellationException e) {}
            assertTrue(f.isCancelled());
            assertTrue(f.isDone());
        } finally {
            rp.stop();
        }
    }
 
Example 17
Project: lazycat   File: WsWebSocketContainer.java   View Source Code Vote up 4 votes
private static void writeRequest(AsyncChannelWrapper channel, ByteBuffer request, long timeout)
		throws TimeoutException, InterruptedException, ExecutionException {
	int toWrite = request.limit();

	Future<Integer> fWrite = channel.write(request);
	Integer thisWrite = fWrite.get(timeout, TimeUnit.MILLISECONDS);
	toWrite -= thisWrite.intValue();

	while (toWrite > 0) {
		fWrite = channel.write(request);
		thisWrite = fWrite.get(timeout, TimeUnit.MILLISECONDS);
		toWrite -= thisWrite.intValue();
	}
}
 
Example 18
Project: openjdk-jdk10   File: Main.java   View Source Code Vote up 4 votes
public static void main(String[] args) throws Exception {

        ModuleFinder finder = ModuleFinder.of(MODS_DIR);
        ModuleLayer layerBoot = ModuleLayer.boot();

        Configuration cf = layerBoot
                .configuration()
                .resolve(ModuleFinder.of(), finder, Set.of(MODULE_NAME));

        Module testModule = Main.class.getModule();
        ClassLoader scl = ClassLoader.getSystemClassLoader();

        // Create an unique module/class loader in a layer above the boot layer.
        // Export this module to the jdk.test/test package.
        Callable<Void> task = new Callable<Void>() {
            @Override
            public Void call() throws Exception {
                ModuleLayer layer = ModuleLayer.boot().defineModulesWithOneLoader(cf, scl);
                Module transletModule = layer.findModule(MODULE_NAME).get();
                testModule.addExports("test", transletModule);
                Class<?> c = layer.findLoader(MODULE_NAME).loadClass("translet.Main");
                Method method = c.getDeclaredMethod("go");
                method.invoke(null);
                return null;
            }
        };

        List<Future<Void>> results = new ArrayList<>();

        // Repeatedly create the layer above stressing the exportation of
        // package jdk.test/test to several different modules.
        ExecutorService pool = Executors.newFixedThreadPool(Math.min(100, Runtime.getRuntime().availableProcessors()*10));
        try {
            for (int i = 0; i < 10000; i++) {
                results.add(pool.submit(task));
            }
        } finally {
            pool.shutdown();
        }

        int passed = 0;
        int failed = 0;

        // The failed state should be 0, the created modules in layers above the
        // boot layer should be allowed access to the contents of the jdk.test/test
        // package since that package was exported to the transletModule above.
        for (Future<Void> result : results) {
            try {
                result.get();
                passed++;
            } catch (Throwable x) {
                x.printStackTrace();
                failed++;
            }
        }

        System.out.println("passed: " + passed);
        System.out.println("failed: " + failed);
    }
 
Example 19
Project: r2-streamer-java   File: EpubContainer.java   View Source Code Vote up 4 votes
@Override
public InputStream rawDataInputStream(final String relativePath) throws NullPointerException {
    try {
        //ZipEntry zipEntry = zipFile.getEntry(relativePath);
        /*InputStream inputStream = zipFile.getInputStream(zipEntry);
        ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
        int bytesRead;
        byte[] byteArray = new byte[4069];
        while ((bytesRead = inputStream.read(byteArray)) != -1){
            byteArrayOutputStream.write(byteArray, 0, bytesRead);
        }

        byteArrayOutputStream.flush();
        byte[] streamArray = byteArrayOutputStream.toByteArray();
        ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(streamArray);*/

        Callable<ByteArrayInputStream> callable = new Callable<ByteArrayInputStream>() {
            @Override
            public ByteArrayInputStream call() throws Exception {
                ZipEntry zipEntry = zipFile.getEntry(relativePath);
                InputStream inputStream = zipFile.getInputStream(zipEntry);
                ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
                long BUFFER_SIZE = 16 * 1024;
                byte[] byteArray = new byte[(int) BUFFER_SIZE];
                int bytesRead;
                while ((bytesRead = inputStream.read(byteArray)) != -1) {
                    byteArrayOutputStream.write(byteArray, 0, bytesRead);
                }

                byteArrayOutputStream.flush();
                byte[] streamArray = byteArrayOutputStream.toByteArray();
                return new ByteArrayInputStream(streamArray);
            }
        };

        ExecutorService executorService = Executors.newCachedThreadPool();
        Future<ByteArrayInputStream> future = executorService.submit(callable);
        return future.get();
    } catch (InterruptedException | ExecutionException e) {
        e.printStackTrace();
    }
    return null;
}
 
Example 20
Project: shabdiz   File: TimeoutExecutorService.java   View Source Code Vote up 3 votes
/**
 * Await completion of a given task for a given timeout.
 *
 * @param <Result> the type of the result that is returned by the task
 * @param task the task to await its execution
 * @param time the maximum duration to wait for the task completion
 * @param time_unit the unit of the maximum duration to wait for the task completion
 * @return the result of the task
 * @throws InterruptedException the interrupted exception
 * @throws ExecutionException the execution exception
 * @throws TimeoutException the timeout exception
 */
public static <Result> Result awaitCompletion(final Callable<Result> task, final long time, final TimeUnit time_unit) throws InterruptedException, ExecutionException, TimeoutException {

    final Future<Result> future_result = TIMEOUT_EXECUTOR_SERVICE_INSTANCE.submit(task);
    try {
        return future_result.get(time, time_unit);
    }
    finally {
        future_result.cancel(true);
        TIMEOUT_EXECUTOR_SERVICE_INSTANCE.purge();
    }
}