Example usage for java.util.concurrent Callable Callable

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

Introduction

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

Prototype

Callable

Source Link

Usage

From source file:org.apache.abdera2.common.protocol.Session.java

public <T extends ClientResponse> Callable<T> getTask(final String uri, final RequestOptions options) {
    return new Callable<T>() {
        public T call() throws Exception {
            return (T) get(uri, options);
        }/*from  w  w  w .j  a v a2  s.  c o m*/
    };
}

From source file:com.test.HibernateDerbyLockingTest.java

public void testJDBC() throws Exception {
    final DerbyTemplate template = new DerbyTemplate();
    try {/*from  w ww . j a va2  s.c om*/
        template.doWithStatement(new IStatementCallback() {
            public void execute(Statement statement) throws Exception {
                statement.execute(
                        "CREATE TABLE TEST(\n" + "ID CHAR(36) NOT NULL,\n" + "NAME VARCHAR(255)\n" + ")");
            }
        });
        template.doWithStatement(new IStatementCallback() {
            public void execute(Statement statement) throws Exception {
                statement.execute("INSERT INTO TEST(ID, NAME) VALUES('12345', 'Bob')");
            }
        });

        final LinkedBlockingQueue<String> queue = new LinkedBlockingQueue<String>();

        ExecutorService executorService = Executors.newCachedThreadPool();
        Future<?> submit = executorService.submit(new Callable<Object>() {

            public Object call() throws Exception {
                template.doWithStatement(new IStatementCallback() {
                    public void execute(Statement statement) throws Exception {
                        ResultSet resultSet = statement.executeQuery(
                                "SELECT ID, NAME FROM TEST WHERE ID = '12345' for update with rs");
                        while (resultSet.next()) {
                            String id = resultSet.getString("ID");
                            String name = resultSet.getString("NAME");
                        }
                        try {
                            Thread.sleep(2000);
                        } catch (Throwable t) {
                        }
                        System.out.println("one");
                        queue.add("one");
                        try {
                            Thread.sleep(500);
                        } catch (Throwable t) {
                        }
                    }
                });
                return null;
            }
        });
        Thread.sleep(500);
        Future<?> submit2 = executorService.submit(new Callable<Object>() {
            public Object call() throws Exception {
                template.doWithStatement(new IStatementCallback() {
                    public void execute(Statement statement) throws Exception {
                        ResultSet resultSet = statement.executeQuery(
                                "SELECT ID, NAME FROM TEST WHERE ID = '12345' for update with rr");
                        while (resultSet.next()) {
                            String id = resultSet.getString("ID");
                            String name = resultSet.getString("NAME");
                        }
                        queue.add("two");
                        System.out.println("two");
                    }
                });
                return null;
            }
        });
        submit.get();
        submit2.get();
        assertEquals("one", queue.poll(3, TimeUnit.SECONDS));
        assertEquals("two", queue.poll(3, TimeUnit.SECONDS));
    } finally {
        template.doWithStatement(new IStatementCallback() {
            public void execute(Statement statement) throws Exception {
                statement.execute("DROP TABLE TEST");
            }
        });
    }
}

From source file:eu.eubrazilcc.lvl.storage.NotificationManager.java

private void createWorker() {
    workers.incrementAndGet();/*  ww w  .  j  a  va 2s  . co m*/
    final ListenableFuture<Void> future = TASK_RUNNER.submit(new Callable<Void>() {
        @Override
        public Void call() throws Exception {
            Notification notification;
            do {
                notification = queue.poll();
                if (notification != null) {
                    if (!queue.isEmpty() && workers.get() < MAX_WORKERS) {
                        createWorker();
                    }
                    if (isNotBlank(notification.getScope())) {
                        // broadcast
                        int start = 0;
                        List<ResourceOwner> resourceOwners = null;
                        final MutableLong count = new MutableLong(0l);
                        do {
                            resourceOwners = RESOURCE_OWNER_DAO.list(start, PAGE_SIZE, null, null, null, count);
                            for (final ResourceOwner resourceOwner : resourceOwners) {
                                if (hasRole(notification.getScope(), resourceOwner.getUser())) {
                                    notification.setAddressee(resourceOwner.getUser().getUserid());
                                    NOTIFICATION_DAO.insert(notification);
                                    LOGGER.trace("Notification broadcasted: " + notification);
                                }
                            }
                            start += resourceOwners.size();
                        } while (!resourceOwners.isEmpty());
                    } else {
                        // send to user converting user-names to valid resource-owner-identifiers
                        try {
                            assertValidResourceOwnerId(notification.getAddressee());
                        } catch (Exception ignore) {
                            try {
                                final String ownerid = toResourceOwnerId(notification.getAddressee());
                                notification.setAddressee(ownerid);
                            } catch (Exception ignore2) {
                            }
                        }
                        if (RESOURCE_OWNER_DAO.exist(notification.getAddressee())) {
                            NOTIFICATION_DAO.insert(notification);
                            LOGGER.trace("Notification sent: " + notification);
                        } else {
                            LOGGER.info(
                                    "Discarding notification after checking that the addressee user does not exist: "
                                            + notification);
                        }
                    }
                }
            } while (notification != null);
            return null;
        }
    });
    Futures.addCallback(future, new FutureCallback<Void>() {
        @Override
        public void onSuccess(final Void result) {
            workers.decrementAndGet();
        }

        @Override
        public void onFailure(final Throwable error) {
            workers.decrementAndGet();
        }
    });
}

From source file:com.cloudera.oryx.als.serving.ServerRecommender.java

public ServerRecommender(File localInputDir) throws IOException {
    Preconditions.checkNotNull(localInputDir, "No local dir");

    numCores = ExecutorUtils.getParallelism();
    executor = new ReloadingReference<ExecutorService>(new Callable<ExecutorService>() {
        @Override/*  ww w .  j  a v a  2s  .c  o  m*/
        public ExecutorService call() {
            return Executors.newFixedThreadPool(2 * numCores,
                    new ThreadFactoryBuilder().setDaemon(true).setNameFormat("ServerRecommender-%d").build());
        }
    });

    this.generationManager = new ALSGenerationManager(localInputDir);
    this.generationManager.refresh();
}

From source file:com.wolvereness.renumerated.Renumerated.java

private void process() throws Throwable {
    validateInput();/*from  w  w w  .  ja va2  s .  c om*/

    final MultiProcessor executor = MultiProcessor.newMultiProcessor(cores - 1,
            new ThreadFactoryBuilder().setDaemon(true)
                    .setNameFormat(Renumerated.class.getName() + "-processor-%d")
                    .setUncaughtExceptionHandler(this).build());
    final Future<?> fileCopy = executor.submit(new Callable<Object>() {
        @Override
        public Object call() throws Exception {
            if (original != null) {
                if (original.exists()) {
                    original.delete();
                }
                Files.copy(input, original);
            }
            return null;
        }
    });

    final List<Pair<ZipEntry, Future<byte[]>>> fileEntries = newArrayList();
    final List<Pair<MutableObject<ZipEntry>, Future<byte[]>>> classEntries = newArrayList();
    {
        final ZipFile input = new ZipFile(this.input);
        final Enumeration<? extends ZipEntry> inputEntries = input.entries();
        while (inputEntries.hasMoreElements()) {
            final ZipEntry entry = inputEntries.nextElement();
            final Future<byte[]> future = executor.submit(new Callable<byte[]>() {
                @Override
                public byte[] call() throws Exception {
                    return ByteStreams.toByteArray(input.getInputStream(entry));
                }
            });
            if (entry.getName().endsWith(".class")) {
                classEntries.add(new MutablePair<MutableObject<ZipEntry>, Future<byte[]>>(
                        new MutableObject<ZipEntry>(entry), future));
            } else {
                fileEntries.add(new ImmutablePair<ZipEntry, Future<byte[]>>(entry, future));
            }
        }

        for (final Pair<MutableObject<ZipEntry>, Future<byte[]>> pair : classEntries) {
            final byte[] data = pair.getRight().get();
            pair.setValue(executor.submit(new Callable<byte[]>() {
                String className;
                List<String> fields;

                @Override
                public byte[] call() throws Exception {
                    try {
                        return method();
                    } catch (final Exception ex) {
                        throw new Exception(pair.getLeft().getValue().getName(), ex);
                    }
                }

                private byte[] method() throws Exception {
                    final ClassReader clazz = new ClassReader(data);
                    clazz.accept(new ClassVisitor(ASM4) {
                        @Override
                        public void visit(final int version, final int access, final String name,
                                final String signature, final String superName, final String[] interfaces) {
                            if (superName.equals("java/lang/Enum")) {
                                className = name;
                            }
                        }

                        @Override
                        public FieldVisitor visitField(final int access, final String name, final String desc,
                                final String signature, final Object value) {
                            if (className != null && (access & 0x4000) != 0) {
                                List<String> fieldNames = fields;
                                if (fieldNames == null) {
                                    fieldNames = fields = newArrayList();
                                }
                                fieldNames.add(name);
                            }
                            return null;
                        }
                    }, ClassReader.SKIP_CODE);

                    if (className == null)
                        return data;

                    final String classDescriptor = Type.getObjectType(className).getDescriptor();

                    final ClassWriter writer = new ClassWriter(0);
                    clazz.accept(new ClassVisitor(ASM4, writer) {
                        @Override
                        public MethodVisitor visitMethod(final int access, final String name, final String desc,
                                final String signature, final String[] exceptions) {
                            final MethodVisitor methodVisitor = super.visitMethod(access, name, desc, signature,
                                    exceptions);
                            if (!name.equals("<clinit>")) {
                                return methodVisitor;
                            }
                            return new MethodVisitor(ASM4, methodVisitor) {
                                final Iterator<String> it = fields.iterator();
                                boolean active;
                                String lastName;

                                @Override
                                public void visitTypeInsn(final int opcode, final String type) {
                                    if (!active && it.hasNext()) {
                                        // Initiate state machine
                                        if (opcode != NEW)
                                            throw new AssertionError("Unprepared for " + opcode + " on " + type
                                                    + " in " + className);
                                        active = true;
                                    }
                                    super.visitTypeInsn(opcode, type);
                                }

                                @Override
                                public void visitLdcInsn(final Object cst) {
                                    if (active && lastName == null) {
                                        if (!(cst instanceof String))
                                            throw new AssertionError(
                                                    "Unprepared for " + cst + " in " + className);
                                        // Switch the first constant in the Enum constructor
                                        super.visitLdcInsn(lastName = it.next());
                                    } else {
                                        super.visitLdcInsn(cst);
                                    }
                                }

                                @Override
                                public void visitFieldInsn(final int opcode, final String owner,
                                        final String name, final String desc) {
                                    if (opcode == PUTSTATIC && active && lastName != null
                                            && owner.equals(className) && desc.equals(classDescriptor)
                                            && name.equals(lastName)) {
                                        // Finish the current state machine
                                        active = false;
                                        lastName = null;
                                    }
                                    super.visitFieldInsn(opcode, owner, name, desc);
                                }
                            };
                        }
                    }, ClassReader.EXPAND_FRAMES);

                    final MutableObject<ZipEntry> key = pair.getLeft();
                    key.setValue(new ZipEntry(key.getValue().getName()));
                    return writer.toByteArray();
                }
            }));
        }

        for (final Pair<ZipEntry, Future<byte[]>> pair : fileEntries) {
            pair.getRight().get();
        }

        input.close();
    }

    fileCopy.get();

    FileOutputStream fileOut = null;
    JarOutputStream jar = null;
    try {
        jar = new JarOutputStream(fileOut = new FileOutputStream(output));
        for (final Pair<ZipEntry, Future<byte[]>> fileEntry : fileEntries) {
            jar.putNextEntry(fileEntry.getLeft());
            jar.write(fileEntry.getRight().get());
        }
        for (final Pair<MutableObject<ZipEntry>, Future<byte[]>> classEntry : classEntries) {
            final byte[] data = classEntry.getRight().get();
            final ZipEntry entry = classEntry.getLeft().getValue();
            entry.setSize(data.length);
            jar.putNextEntry(entry);
            jar.write(data);
        }
    } finally {
        if (jar != null) {
            try {
                jar.close();
            } catch (final IOException ex) {
            }
        }
        if (fileOut != null) {
            try {
                fileOut.close();
            } catch (final IOException ex) {
            }
        }
    }

    final Pair<Thread, Throwable> uncaught = this.uncaught;
    if (uncaught != null)
        throw new MojoExecutionException(String.format("Uncaught exception in %s", uncaught.getLeft()),
                uncaught.getRight());
}

From source file:gobblin.hive.HiveRegister.java

/**
 * Register a table or partition given a {@link HiveSpec}. This method is asynchronous and returns immediately.
 * This methods evaluates the {@link Predicate}s and executes the {@link Activity}s specified in the
 * {@link HiveSpec}. The actual registration happens in {@link #registerPath(HiveSpec)}, which subclasses
 * should implement.// w w w .  java  2s .  c o m
 *
 * @return a {@link ListenableFuture} for the process of registering the given {@link HiveSpec}.
 */
public ListenableFuture<Void> register(final HiveSpec spec) {
    ListenableFuture<Void> future = this.executor.submit(new Callable<Void>() {

        @Override
        public Void call() throws Exception {

            if (spec instanceof HiveSpecWithPredicates && !evaluatePredicates((HiveSpecWithPredicates) spec)) {
                log.info("Skipping " + spec + " since predicates return false");
                return null;
            }

            if (spec instanceof HiveSpecWithPreActivities) {
                for (Activity activity : ((HiveSpecWithPreActivities) spec).getPreActivities()) {
                    activity.execute(HiveRegister.this);
                }
            }

            registerPath(spec);

            if (spec instanceof HiveSpecWithPostActivities) {
                for (Activity activity : ((HiveSpecWithPostActivities) spec).getPostActivities()) {
                    activity.execute(HiveRegister.this);
                }
            }

            return null;
        }

    });
    this.futures.put(getSpecId(spec), future);
    return future;
}

From source file:com.microsoft.windowsazure.management.sql.DatabaseOperationOperationsImpl.java

/**
* Returns information about a specific operation by using the operation
* Guid./*from ww w . j  a  va 2 s. co  m*/
*
* @param serverName Required. The name of the Azure SQL Database Server
* where the database is hosted.
* @param operationGuid Required. The Guid of the Azure SQL Database
* operation to be obtained.
* @return Represents the database operation for a given operation Guid.
*/
@Override
public Future<DatabaseOperationGetResponse> getAsync(final String serverName, final String operationGuid) {
    return this.getClient().getExecutorService().submit(new Callable<DatabaseOperationGetResponse>() {
        @Override
        public DatabaseOperationGetResponse call() throws Exception {
            return get(serverName, operationGuid);
        }
    });
}

From source file:com.infinities.skyport.timeout.ServiceProviderTimeLimiter.java

public <T> T newProxy(final T target, Class<T> interfaceType, final Object configuration)
        throws InitializationException {
    if (target == null) {
        return target;
    }/*w  w  w . j a  v  a  2 s.co  m*/
    checkNotNull(interfaceType);
    checkNotNull(configuration);
    checkArgument(interfaceType.isInterface(), "interfaceType must be an interface type");

    checkMethodOwnFunctionConfiguration(interfaceType, configuration);

    final Set<Method> interruptibleMethods = findInterruptibleMethods(interfaceType);

    InvocationHandler handler = new InvocationHandler() {

        @Override
        public Object invoke(Object obj, final Method method, final Object[] args) throws Throwable {
            String methodName = method.getName();
            long timeoutDuration = 0;
            TimeUnit timeUnit = TimeUnit.SECONDS;
            try {
                FunctionConfiguration functionConfiguration = (FunctionConfiguration) PropertyUtils
                        .getProperty(configuration, methodName);
                Time timeout = functionConfiguration.getTimeout();
                if (timeout != null) {
                    timeoutDuration = timeout.getNumber();
                    timeUnit = timeout.getUnit();
                }
            } catch (NoSuchMethodException | IllegalArgumentException e) {
                if (IGNORED_SET.contains(method.getName()) || method.getAnnotation(Deprecated.class) != null) {
                    return method.invoke(target, args);
                }
                throwCause(e, false);
                throw new AssertionError("can't get here");
            } catch (InvocationTargetException e) {
                throwCause(e, false);
                throw new AssertionError("can't get here");
            }
            Callable<Object> callable = new Callable<Object>() {

                @Override
                public Object call() throws Exception {
                    try {
                        return method.invoke(target, args);
                    } catch (InvocationTargetException e) {
                        throwCause(e, false);
                        throw new AssertionError("can't get here");
                    }
                }
            };
            if (timeoutDuration > 0) {
                return limiter.callWithTimeout(callable, timeoutDuration, timeUnit,
                        interruptibleMethods.contains(method));
            } else {
                // no timeout
                return method.invoke(target, args);
            }
        }
    };
    return newProxy(interfaceType, handler);
}

From source file:com.collective.celos.ci.mode.TestTask.java

private List<Future> submitTestRuns() {
    ExecutorService executor = Executors.newCachedThreadPool();
    List<Future> futures = Lists.newArrayList();
    for (final TestRun testRun : testRuns) {
        Callable callable = new Callable<Void>() {
            @Override/* w  w  w .  j  a  v  a  2 s .com*/
            public Void call() throws Exception {
                testRun.start();
                return null;
            }
        };
        futures.add(executor.submit(callable));
    }
    return futures;
}