Example usage for java.util.concurrent TimeoutException TimeoutException

List of usage examples for java.util.concurrent TimeoutException TimeoutException

Introduction

In this page you can find the example usage for java.util.concurrent TimeoutException TimeoutException.

Prototype

public TimeoutException() 

Source Link

Document

Constructs a TimeoutException with no specified detail message.

Usage

From source file:com.asakusafw.runtime.util.cache.HadoopFileCacheRepositoryTest.java

/**
 * Conflict cache creation.//from   w ww .  j  a  v a 2  s.c  o  m
 * @throws Exception if failed
 */
@Test
public void conflict() throws Exception {
    File source = folder.newFile();
    byte[] bytes = new byte[1024 * 1024];
    try (OutputStream output = new FileOutputStream(source)) {
        for (int i = 0, n = 50; i < n; i++) {
            output.write(bytes);
        }
    }

    Path path = path(source);
    File cacheRepo = folder.newFolder();
    Configuration configuration = new ConfigurationProvider().newInstance();
    LockProvider<Path> locks = new LocalFileLockProvider<>(folder.newFolder());
    RetryStrategy retrier = new ConstantRetryStrategy(30, 100, 200);
    FileCacheRepository cache = new HadoopFileCacheRepository(configuration, path(cacheRepo), locks, retrier);

    List<Future<Path>> futures = new ArrayList<>();
    int count = 10;
    CountDownLatch latch = new CountDownLatch(count);
    ExecutorService executor = Executors.newFixedThreadPool(count);
    try {
        for (int i = 0; i < count; i++) {
            String label = String.format("thread-%d", i);
            futures.add(executor.submit(() -> {
                LOG.info("Wait: resolve @" + label);
                latch.countDown();
                if (latch.await(5, TimeUnit.SECONDS) == false) {
                    throw new TimeoutException();
                }
                LOG.info("Start: resolve @" + label);
                Path result = cache.resolve(path);

                LOG.info("Finish: resolve @" + label);
                return result;
            }));
        }
        executor.shutdown();
        if (executor.awaitTermination(30, TimeUnit.SECONDS) == false) {
            throw new TimeoutException();
        }
    } finally {
        executor.shutdownNow();
    }
    for (Future<Path> future : futures) {
        future.get();
    }
}

From source file:com.netflix.curator.framework.recipes.locks.TestInterProcessSemaphore.java

@Test
public void testMaxPerSession() throws Exception {
    final int CLIENT_QTY = 10;
    final int LOOP_QTY = 100;
    final Random random = new Random();
    final int SESSION_MAX = random.nextInt(75) + 25;

    List<Future<Object>> futures = Lists.newArrayList();
    ExecutorService service = Executors.newCachedThreadPool();
    final Counter counter = new Counter();
    final AtomicInteger available = new AtomicInteger(SESSION_MAX);
    for (int i = 0; i < CLIENT_QTY; ++i) {
        futures.add(service.submit(new Callable<Object>() {
            @Override/*from   w w w .j  a  v a  2  s  . c o  m*/
            public Object call() throws Exception {
                CuratorFramework client = CuratorFrameworkFactory.newClient(server.getConnectString(),
                        new RetryOneTime(1));
                client.start();
                try {
                    InterProcessSemaphoreV2 semaphore = new InterProcessSemaphoreV2(client, "/test",
                            SESSION_MAX);

                    for (int i = 0; i < LOOP_QTY; ++i) {
                        long start = System.currentTimeMillis();
                        int thisQty;
                        synchronized (available) {
                            if ((System.currentTimeMillis() - start) > 10000) {
                                throw new TimeoutException();
                            }
                            while (available.get() == 0) {
                                available.wait(10000);
                            }

                            thisQty = (available.get() > 1) ? (random.nextInt(available.get()) + 1) : 1;

                            available.addAndGet(-1 * thisQty);
                            Assert.assertTrue(available.get() >= 0);
                        }
                        Collection<Lease> leases = semaphore.acquire(thisQty, 10, TimeUnit.SECONDS);
                        Assert.assertNotNull(leases);
                        try {
                            synchronized (counter) {
                                counter.currentCount += thisQty;
                                if (counter.currentCount > counter.maxCount) {
                                    counter.maxCount = counter.currentCount;
                                }
                            }
                            Thread.sleep(random.nextInt(25));
                        } finally {
                            synchronized (counter) {
                                counter.currentCount -= thisQty;
                            }
                            semaphore.returnAll(leases);
                            synchronized (available) {
                                available.addAndGet(thisQty);
                                available.notifyAll();
                            }
                        }
                    }
                } finally {
                    client.close();
                }
                return null;
            }
        }));
    }

    for (Future<Object> f : futures) {
        f.get();
    }

    synchronized (counter) {
        Assert.assertTrue(counter.currentCount == 0);
        Assert.assertTrue(counter.maxCount > 0);
        Assert.assertTrue(counter.maxCount <= SESSION_MAX);
        System.out.println(counter.maxCount);
    }
}

From source file:org.cloudifysource.esc.driver.provisioning.byon.DynamicByonProvisioningDriver.java

@Override
protected MachineDetails createServer(final String serverName, final long endTime,
        final ComputeTemplate template) throws CloudProvisioningException, TimeoutException {

    String ip;/* w w w. ja  v  a  2 s  .  c om*/
    synchronized (mutex) {
        ip = managementMachines.removeFirst();
    }

    MachineDetails machine = createMachine(serverName, template, ip);

    if (System.currentTimeMillis() > endTime) {
        throw new TimeoutException();
    }
    logger.info("Successfully started machine [" + ip + "]");

    return machine;
}

From source file:com.epam.reportportal.apache.http.impl.conn.TestPoolingHttpClientConnectionManager.java

@Test(expected = ConnectionPoolTimeoutException.class)
public void testLeaseFutureTimeout() throws Exception {
    final HttpHost target = new HttpHost("localhost");
    final HttpRoute route = new HttpRoute(target);

    Mockito.when(future.isCancelled()).thenReturn(Boolean.TRUE);
    Mockito.when(future.get(1, TimeUnit.SECONDS)).thenThrow(new TimeoutException());
    Mockito.when(pool.lease(route, null, null)).thenReturn(future);

    final ConnectionRequest connRequest1 = mgr.requestConnection(route, null);
    connRequest1.get(1, TimeUnit.SECONDS);
}

From source file:net.sf.xmm.moviemanager.http.HttpUtil.java

public HTTPResult readData(URL url) throws TimeoutException, Exception {

    if (!isSetup())
        setup();/*from  w ww. j  av  a  2  s. c om*/

    GetMethod method = new GetMethod(url.toString());
    int statusCode = client.executeMethod(method);

    if (statusCode != HttpStatus.SC_OK) {
        log.debug("HTTP StatusCode not HttpStatus.SC_OK:" + method.getStatusLine());
        log.debug("For url:" + url.toString());
    }

    if (statusCode == HttpStatus.SC_REQUEST_TIMEOUT) {
        throw new TimeoutException();
    }

    //java.io.BufferedReader stream = new java.io.BufferedReader(new java.io.InputStreamReader(method.getResponseBodyAsStream(), "ISO-8859-1"));

    StringBuffer data = new StringBuffer();

    // Saves the page data in a string buffer... 
    String chrSet = method.getResponseCharSet();
    InputStream input = method.getResponseBodyAsStream();
    ByteArrayOutputStream temp = new ByteArrayOutputStream();
    byte[] buff = new byte[1500];
    int read;
    while ((read = input.read(buff)) >= 0) {
        temp.write(buff, 0, read);
    }
    input.close();
    temp.flush();
    buff = temp.toByteArray();
    temp.close();
    data.append(new String(buff, chrSet));

    return new HTTPResult(url, statusCode == HttpStatus.SC_OK ? data : null, method.getStatusLine());
}

From source file:fr.inria.atlanmod.neoemf.datastore.estores.impl.DirectWriteHbaseResourceEStoreImpl.java

protected Object set(NeoEMFEObject object, EAttribute eAttribute, int index, Object value) {
    Object oldValue = isSet((InternalEObject) object, eAttribute) ? get(object, eAttribute, index) : null;
    try {//from  w w w  .  ja v  a 2s  .  com
        if (!eAttribute.isMany()) {
            Put put = new Put(Bytes.toBytes(object.neoemfId()));
            put.add(PROPERTY_FAMILY, Bytes.toBytes(eAttribute.getName()),
                    Bytes.toBytes(serializeValue(eAttribute, value)));
            table.put(put);
        } else {
            try {
                String[] array;
                boolean passed = false;
                int attemp = 0;

                do {
                    array = (String[]) getFromTable(object, eAttribute);
                    //array = (String[]) ArrayUtils.add(array, index, serializeValue(eAttribute, value));
                    Put put = new Put(Bytes.toBytes(object.neoemfId())).add(PROPERTY_FAMILY,
                            Bytes.toBytes(eAttribute.getName()),
                            NeoEMFUtil.EncoderUtil.toBytes((String[]) ArrayUtils.add(array, index,
                                    serializeValue(eAttribute, value))));
                    passed = table.checkAndPut(Bytes.toBytes(object.neoemfId()), PROPERTY_FAMILY,
                            Bytes.toBytes(eAttribute.getName()),
                            array == null ? null : NeoEMFUtil.EncoderUtil.toBytes(array), put);
                    if (!passed) {
                        if (attemp > ATTEMP_TIMES_DEFAULT)
                            throw new TimeoutException();
                        Thread.sleep((++attemp) * SLEEP_DEFAULT);
                    }

                } while (!passed);

            } catch (IOException e) {
                Logger.log(Logger.SEVERITY_ERROR,
                        MessageFormat.format("Unable to set ''{0}'' to ''{1}'' for element ''{2}''", value,
                                eAttribute.getName(), object));
            } catch (TimeoutException e) {
                Logger.log(Logger.SEVERITY_ERROR,
                        MessageFormat.format(
                                "Unable to set ''{0}'' to ''{1}'' for element ''{2}'' after ''{3}'' times",
                                value, eAttribute.getName(), object, ATTEMP_TIMES_DEFAULT));
                e.printStackTrace();
            } catch (InterruptedException e) {
                Logger.log(Logger.SEVERITY_ERROR, MessageFormat.format(
                        "InterruptedException while updating element ''{0}''.\n{1}", object, e.getMessage()));
                e.printStackTrace();
            }
        }
    } catch (IOException e) {
        Logger.log(Logger.SEVERITY_ERROR,
                MessageFormat.format("Unable to set information for element ''{0}''", object));
    }
    return oldValue;
}

From source file:com.sap.research.connectivity.gw.GWOperationsUtils.java

public String getMetadataString(String url, String user, String pass, String host, String port, int timeOut)
        throws Exception {
    String returnString = "";

    try {// www .j av  a  2  s  . c  om
        String execArgs[] = new String[] { "java", "-jar",
                System.getProperty("user.home") + SEPARATOR + "appToRetrieveOdataMetadata.jar", url, user, pass,
                host, port };

        final Process theProcess = Runtime.getRuntime().exec(execArgs);

        Callable<String> call = new Callable<String>() {
            public String call() throws Exception {
                String returnString = "";
                try {
                    BufferedReader inStream = new BufferedReader(
                            new InputStreamReader(theProcess.getInputStream()));
                    returnString = IOUtils.toString(inStream);
                    IOUtils.closeQuietly(inStream);
                    //if (theProcess.exitValue() != 0)
                    theProcess.waitFor();
                } catch (InterruptedException e) {
                    throw new TimeoutException();
                    //log.severe("The call to the Gateway Service was interrupted.");
                }
                return returnString;
            }
        };

        final ExecutorService theExecutor = Executors.newSingleThreadExecutor();
        Future<String> futureResultOfCall = theExecutor.submit(call);
        try {
            returnString = futureResultOfCall.get(timeOut, TimeUnit.SECONDS);
        } catch (TimeoutException ex) {
            throw new TimeoutException(
                    "The Gateway Service call timed out. Please try again or check your settings.");
        } catch (ExecutionException ex) {
            throw new RuntimeException("The Gateway Service call did not complete due to an execution error. "
                    + ex.getCause().getLocalizedMessage());
        } finally {
            theExecutor.shutdownNow();
        }
    } catch (InterruptedException ex) {
        throw new InterruptedException(
                "The Gateway Service call did not complete due to an unexpected interruption.");
    } catch (IOException e) {
        throw new IOException("Error when retrieving metadata from the Gateway Service.");
    }

    return returnString;
}

From source file:one.nio.mem.OffheapMap.java

public Record<K, V> lockRecordForRead(K key, long timeout) throws TimeoutException {
    long hashCode = hashCode(key);
    RWLock lock = lockFor(hashCode);//from  w w  w. jav  a2s . c o  m
    if (!lock.lockRead(timeout)) {
        throw new TimeoutException();
    }
    return createRecord(key, hashCode, lock);
}

From source file:org.cloudifysource.dsl.internal.tools.download.ResourceDownloader.java

private void getResource(final URL downloadURL, final File destination)
        throws ResourceDownloadException, TimeoutException {

    final long end = System.currentTimeMillis() + this.timeoutInMillis;
    final InputStream is = openConnectionInputStream(downloadURL);
    if (is == null) {
        logger.log(Level.WARNING, "connection input stream failed to initialize");
        throw new ResourceDownloadException(
                "Failed getting " + this.resourceUrl + " to " + destination.getAbsolutePath());
    }/*from  w  ww. j a  v a  2 s . c  o m*/

    final File temporaryDestination = createTemporaryDestinationFile(destination);

    final OutputStream os = getFileOutputString(temporaryDestination);
    boolean finished = false;
    try {
        final byte[] buffer = new byte[BUFFER_SIZE];
        int length;
        if (logger.isLoggable(Level.FINE)) {
            logger.fine("Downloading " + downloadURL.toString() + " to " + this.resourceDest);
        }
        while ((length = is.read(buffer)) >= 0) {
            os.write(buffer, 0, length);
            if (end < System.currentTimeMillis()) {
                throw new TimeoutException();
            }
        }
        finished = true;

    } catch (IOException e) {
        logger.warning("Failed downloading resource from " + downloadURL.toString() + ". Reason was: "
                + e.getMessage());
        throw new ResourceDownloadException("Failed downloading resource. Reason was: " + e.getMessage(), e);
    } finally {
        IOUtils.closeQuietly(os);
        IOUtils.closeQuietly(is);

        if (!finished) {
            logger.log(Level.WARNING, "Download did not complete successfully. deleting file.");
            FileUtils.deleteQuietly(temporaryDestination);
            FileUtils.deleteQuietly(destination);

        }
    }
    if (finished) {
        try {

            FileUtils.copyFile(temporaryDestination, destination);

        } catch (IOException e) {
            if (destination.exists()) {
                logger.warning("Failed to write downloaded file to destination: " + destination
                        + ". Destination file already exists. "
                        + "This probably indicates a concurrent download of the same file.");
            } else {
                throw new ResourceDownloadException(
                        "Failed to copy downloaded file to target location: " + e.getMessage(), e);
            }

        } finally {
            FileUtils.deleteQuietly(temporaryDestination);
        }
    }

}

From source file:org.fusesource.meshkeeper.distribution.LaunchClient.java

public void waitForAvailableAgents(int agentCount, long timeout, TimeUnit unit)
        throws InterruptedException, TimeoutException {
    timeout = unit.toNanos(timeout);/*from ww  w.  j av  a2  s.  c om*/
    synchronized (this) {
        long start = System.nanoTime();
        while (timeout > 0 && agentProps.isEmpty()) {
            wait(timeout);
            if (agentProps.size() >= agentCount) {
                return;
            }
            timeout -= System.nanoTime() - start;
        }

        if (agentProps.isEmpty()) {
            throw new TimeoutException();
        }
    }
}