Example usage for java.util.concurrent FutureTask FutureTask

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

Introduction

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

Prototype

public FutureTask(Callable<V> callable) 

Source Link

Document

Creates a FutureTask that will, upon running, execute the given Callable .

Usage

From source file:com.github.vatbub.tictactoe.view.AnimationThreadPoolExecutor.java

@SuppressWarnings("unused")
public <T> Future<T> submitWaitForUnlock(Callable<T> task) {
    Callable<T> effectiveTask = () -> {
        // PrintStreams magically don't make the wait loop hang
        PrintStream nullStream = new PrintStream(new OutputStream() {
            public void write(int b) {
                //DO NOTHING
            }//  www .ja  v  a2  s  .  co m
        });
        while (isBlocked()) {
            nullStream.println("Waiting...");
        }
        // run
        FutureTask<T> effectiveCall = new FutureTask<>(task);
        Platform.runLater(effectiveCall);
        return effectiveCall.get();
    };
    return super.schedule(effectiveTask, 0, NANOSECONDS);
}

From source file:org.atomserver.ThrottledAtomServer.java

/**
 * Execute the CallableTask on a ThreadPoolTaskExecutor. <br/>
 * NOTE: the standard Exception handling of AtomServer still happens in the AtomServer class.
 * Any Exception handling done here is for Exceptions that actually are thrown this far up
 * the food chain -- Exceptions that pertain directly to the TaskExecutor --
 * for example, TimeoutException or ExecutionException.
 *
 * @param request      The Abdera RequestContext
 * @param callableTask The CallableTask, which shoudl just be a wrapped call to
 *                     the corresponding super task.
 * @return The Abdera ResponseContext// ww w  .  jav a2  s . c o m
 */
private ResponseContext executePooledTask(final RequestContext request,
        final Callable<ResponseContext> callableTask) {
    ResponseContext response = null;
    Abdera abdera = request.getServiceContext().getAbdera();

    try {

        FutureTask<ResponseContext> futureTask = new FutureTask(callableTask);
        threadPool.execute(futureTask);

        try {
            logger.debug("starting to wait for the task to complete");
            response = futureTask.get(taskTimeout, TimeUnit.MILLISECONDS);

        } catch (InterruptedException e) {
            // InterruptedException - if the current thread was interrupted while waiting
            // Re-assert the thread's interrupted status
            Thread.currentThread().interrupt();

            logger.error("InterruptedException in executePooledTask: Cause= " + e.getCause() + " Message= "
                    + e.getMessage(), e);
            return getAtomServer().servererror(abdera, request,
                    "InterruptedException occurred:: " + e.getCause(), e);
        } catch (ExecutionException e) {
            // ExecutionException - if the computation threw an exception
            // Because all Exception handling is done in the super class; AtomServer, we should never get this
            logger.error("ExecutionException in executePooledTask: Cause= " + e.getCause() + " Message= "
                    + e.getMessage(), e);
            return getAtomServer().servererror(abdera, request, "ExecutionException occurred:: " + e.getCause(),
                    e);
        } catch (TimeoutException e) {
            //  TimeoutException - if the wait timed out
            logger.error("TimeoutException in executePooledTask: Cause= " + e.getCause() + " Message= "
                    + e.getMessage(), e);
            return getAtomServer().servererror(abdera, request, "TimeoutException occurred:: " + e.getCause(),
                    e);
        } catch (Exception e) {
            logger.error("Unknown Exception in executePooledTask: Cause= " + e.getCause() + " Message= "
                    + e.getMessage(), e);
            return getAtomServer().servererror(abdera, request, "Unknown Exception occurred:: " + e.getCause(),
                    e);

        } finally {
            // Best practice is to cancel tasks whose result is no longer needed
            // NOTE; task.cancel() is harmless if the task has already completed
            // Interrupt if running...
            futureTask.cancel(true);

            // Help out the garbage collector
            futureTask = null;
        }

    } finally {
        // Log all thread pool statistics at INFO level.
        //  This information is very critical in understanding the effectiveness of the pool
        logThreadPoolStats();
    }
    return response;
}

From source file:io.teak.sdk.DeviceConfiguration.java

public DeviceConfiguration(@NonNull final Context context, @NonNull AppConfiguration appConfiguration) {
    if (android.os.Build.VERSION.RELEASE == null) {
        this.platformString = "android_unknown";
    } else {/*www. j av  a 2s .c om*/
        this.platformString = "android_" + android.os.Build.VERSION.RELEASE;
    }

    // Preferences file
    {
        SharedPreferences tempPreferences = null;
        try {
            tempPreferences = context.getSharedPreferences(Teak.PREFERENCES_FILE, Context.MODE_PRIVATE);
        } catch (Exception e) {
            Log.e(LOG_TAG, "Error calling getSharedPreferences(). " + Log.getStackTraceString(e));
        } finally {
            this.preferences = tempPreferences;
        }

        if (this.preferences == null) {
            Log.e(LOG_TAG, "getSharedPreferences() returned null. Some caching is disabled.");
        }
    }

    // Device model/manufacturer
    // https://raw.githubusercontent.com/jaredrummler/AndroidDeviceNames/master/library/src/main/java/com/jaredrummler/android/device/DeviceName.java
    {
        this.deviceManufacturer = Build.MANUFACTURER == null ? "" : Build.MANUFACTURER;
        this.deviceModel = Build.MODEL == null ? "" : Build.MODEL;
        if (this.deviceModel.startsWith(Build.MANUFACTURER)) {
            this.deviceFallback = capitalize(Build.MODEL);
        } else {
            this.deviceFallback = capitalize(Build.MANUFACTURER) + " " + Build.MODEL;
        }
    }

    // Device id
    {
        String tempDeviceId = null;
        try {
            tempDeviceId = UUID.nameUUIDFromBytes(android.os.Build.SERIAL.getBytes("utf8")).toString();
        } catch (Exception e) {
            Log.e(LOG_TAG, "android.os.Build.SERIAL not available, falling back to Settings.Secure.ANDROID_ID. "
                    + Log.getStackTraceString(e));
        }

        if (tempDeviceId == null) {
            try {
                String androidId = Settings.Secure.getString(context.getContentResolver(),
                        Settings.Secure.ANDROID_ID);
                if (androidId.equals("9774d56d682e549c")) {
                    Log.e(LOG_TAG,
                            "Settings.Secure.ANDROID_ID == '9774d56d682e549c', falling back to random UUID stored in preferences.");
                } else {
                    tempDeviceId = UUID.nameUUIDFromBytes(androidId.getBytes("utf8")).toString();
                }
            } catch (Exception e) {
                Log.e(LOG_TAG,
                        "Error generating device id from Settings.Secure.ANDROID_ID, falling back to random UUID stored in preferences. "
                                + Log.getStackTraceString(e));
            }
        }

        if (tempDeviceId == null) {
            if (this.preferences != null) {
                tempDeviceId = this.preferences.getString(PREFERENCE_DEVICE_ID, null);
                if (tempDeviceId == null) {
                    try {
                        String prefDeviceId = UUID.randomUUID().toString();
                        SharedPreferences.Editor editor = this.preferences.edit();
                        editor.putString(PREFERENCE_DEVICE_ID, prefDeviceId);
                        editor.apply();
                        tempDeviceId = prefDeviceId;
                    } catch (Exception e) {
                        Log.e(LOG_TAG,
                                "Error storing random UUID, no more fallbacks. " + Log.getStackTraceString(e));
                    }
                }
            } else {
                Log.e(LOG_TAG,
                        "getSharedPreferences() returned null, unable to store random UUID, no more fallbacks.");
            }
        }

        this.deviceId = tempDeviceId;

        if (this.deviceId == null) {
            return;
        }
    }

    // Kick off GCM request
    if (this.preferences != null) {
        int storedAppVersion = this.preferences.getInt(PREFERENCE_APP_VERSION, 0);
        String storedGcmId = this.preferences.getString(PREFERENCE_GCM_ID, null);
        if (storedAppVersion == appConfiguration.appVersion && storedGcmId != null) {
            // No need to get a new one, so put it on the blocking queue
            if (Teak.isDebug) {
                Log.d(LOG_TAG, "GCM Id found in cache: " + storedGcmId);
            }
            this.gcmId = storedGcmId;
            displayGCMDebugMessage();
        }
    }

    this.gcm = new FutureTask<>(new RetriableTask<>(100, 2000L, new Callable<GoogleCloudMessaging>() {
        @Override
        public GoogleCloudMessaging call() throws Exception {
            return GoogleCloudMessaging.getInstance(context);
        }
    }));
    new Thread(this.gcm).start();

    if (this.gcmId == null) {
        registerForGCM(appConfiguration);
    }

    // Kick off Advertising Info request
    fetchAdvertisingInfo(context);
}

From source file:i5.las2peer.services.videoAdapter.AdapterClass.java

@GET
@Path("playlist")
public HttpResponse getPlaylist(@QueryParam(name = "sub", defaultValue = "*") String subId,
        //@QueryParam(name="username" , defaultValue = "*") String username, 
        @QueryParam(name = "search", defaultValue = "*") String searchString,
        @QueryParam(name = "lat", defaultValue = "*") String lat,
        @QueryParam(name = "lng", defaultValue = "*") String lng,
        @QueryParam(name = "duration", defaultValue = "true") boolean duration,
        @QueryParam(name = "language", defaultValue = "true") boolean language,
        @QueryParam(name = "location", defaultValue = "true") boolean location,
        @QueryParam(name = "relevance", defaultValue = "true") boolean relevance,
        @QueryParam(name = "weightOrder", defaultValue = "true") boolean weightOrder,
        @QueryParam(name = "sequence", defaultValue = "LRDOW") String sequence,
        @QueryParam(name = "mobile", defaultValue = "false") boolean mobile,
        @QueryParam(name = "Authorization", defaultValue = "") String token) {

    String username = null;//from www.j a v a  2  s . c  o  m

    System.out.println("TOKEN: " + token);

    if (token != null) {
        token = token.replace("Bearer ", "");
        username = OIDC.verifyAccessToken(token, userinfo);
    }

    System.out.println("Adapter Service Checkpoint:0 -- request received" + " - User: " + username
            + " - Search Query: " + searchString);

    //Query parameters validation

    if (!isInteger(lat))
        lat = "*";
    if (!isInteger(lng))
        lng = "*";
    if (username.isEmpty() || username.equals("undefined") || username.equals("error")) {
        HttpResponse r = new HttpResponse("User is not signed in!");
        r.setStatus(401);
        return r;
    }
    if (searchString.isEmpty() || searchString.equals("undefined")) {
        HttpResponse r = new HttpResponse("Please enter a valid search query!");
        r.setStatus(400);
        return r;
    }
    /*StopWords sw=new StopWords();
    searchString = sw.remove(searchString);*/

    System.out.println("Stemmed search query: " + searchString);

    dbm = new DatabaseManager();
    dbm.init(driverName, databaseServer, port, database, this.username, password, hostName);

    FutureTask<String> future = new FutureTask<>(new Adapt(searchString, username, lat, lng, dbm, duration,
            location, language, mobile, relevance, weightOrder, sequence, token));
    future.run();
    String annotations = "No Annotation";

    try {

        annotations = future.get();
        //System.out.println("Result="+result);

    } catch (InterruptedException | ExecutionException e) {

        System.out.println("EXCEPTION!!!");
        e.printStackTrace();
    }

    //String annotations = getAndAdapt(searchString, username, id++);

    HttpResponse r = new HttpResponse(annotations);
    r.setStatus(200);
    return r;

}

From source file:com.facebook.FacebookSdk.java

/**
 * This function initializes the Facebook SDK, the behavior of Facebook SDK functions are
 * undetermined if this function is not called. It should be called as early as possible.
 * @param applicationContext The application context
 *///from  w  ww. j  a v  a 2s .co  m
public static synchronized void sdkInitialize(Context applicationContext) {
    if (sdkInitialized == true) {
        return;
    }

    Validate.notNull(applicationContext, "applicationContext");

    // Don't throw for these validations here, just log an error. We'll throw when we actually
    // need them
    Validate.hasFacebookActivity(applicationContext, false);
    Validate.hasInternetPermissions(applicationContext, false);

    FacebookSdk.applicationContext = applicationContext.getApplicationContext();

    // Make sure we've loaded default settings if we haven't already.
    FacebookSdk.loadDefaultsFromMetadata(FacebookSdk.applicationContext);
    // Load app settings from network so that dialog configs are available
    Utility.loadAppSettingsAsync(FacebookSdk.applicationContext, applicationId);
    // Fetch available protocol versions from the apps on the device
    NativeProtocol.updateAllAvailableProtocolVersionsAsync();

    BoltsMeasurementEventListener.getInstance(FacebookSdk.applicationContext);

    cacheDir = FacebookSdk.applicationContext.getCacheDir();

    FutureTask<Void> accessTokenLoadFutureTask = new FutureTask<Void>(new Callable<Void>() {
        @Override
        public Void call() throws Exception {
            AccessTokenManager.getInstance().loadCurrentAccessToken();
            ProfileManager.getInstance().loadCurrentProfile();
            if (AccessToken.getCurrentAccessToken() != null && Profile.getCurrentProfile() == null) {
                // Access token and profile went out of sync due to a network or caching
                // issue, retry
                Profile.fetchProfileForCurrentAccessToken();
            }
            return null;
        }
    });
    getExecutor().execute(accessTokenLoadFutureTask);

    sdkInitialized = true;
}

From source file:org.nuxeo.ecm.core.management.jtajca.CanMonitorTransactionsTest.java

@Test
@LogCaptureFeature.FilterWith(value = CanMonitorTransactionsTest.LogMessageFilter.class)
public void logContainsTxKey() throws InterruptedException, ExecutionException, NoLogCaptureFilterException {
    FutureTask<Boolean> task = new FutureTask<Boolean>(new TestLogRollbackTrace());
    executor.execute(task);/*from w  w  w .ja va2s  .c  o  m*/
    assertThat(task.get(), is(true));
    logCaptureResults.assertHasEvent();
}

From source file:com.betfair.cougar.client.socket.ExecutionVenueNioClient.java

/**
 * Starts the client//from  w  ww.j a v a2 s .c om
 *
 * @return a Future<Boolean> that is true once the connection is established
 */
public synchronized FutureTask<Boolean> start() {
    this.sessionFactory.start();
    if (rpcTimeoutChecker != null) {
        rpcTimeoutChecker.getThread().start();
    }
    final FutureTask<Boolean> futureTask = new FutureTask<Boolean>(new Callable<Boolean>() {
        @Override
        public Boolean call() throws Exception {
            while (!ExecutionVenueNioClient.this.sessionFactory.isConnected()) {
                Thread.sleep(50);
            }
            return true;
        }
    });
    final Thread thread = new Thread(futureTask);
    thread.setDaemon(true);
    thread.start();
    return futureTask;
}

From source file:org.apache.shindig.gadgets.servlet.ConcatProxyServlet.java

/**
 * @param response HttpservletResponse.//from w  ww . ja  va  2s  .  co  m
 * @param concatUri URI representing the concatenated list of resources requested.
 * @return false for cases where concat resources could not be fetched, true for success cases.
 * @throws IOException
 */
private boolean doFetchConcatResources(HttpServletResponse response, ConcatUriManager.ConcatUri concatUri)
        throws IOException {
    // Check for json concat and set output stream.
    ConcatOutputStream cos = null;

    String jsonVar = concatUri.getSplitParam();
    if (jsonVar != null) {
        // JSON-concat mode.
        if (JSON_PARAM_PATTERN.matcher(jsonVar).matches()) {
            cos = new JsonConcatOutputStream(response.getOutputStream(), jsonVar);
        } else {
            response.getOutputStream().println(formatHttpError(HttpServletResponse.SC_BAD_REQUEST,
                    "Bad json variable name " + jsonVar, null));
            return false;
        }
    } else {
        // Standard concat output mode.
        cos = new VerbatimConcatOutputStream(response.getOutputStream());
    }

    List<Pair<Uri, FutureTask<RequestContext>>> futureTasks = new ArrayList<Pair<Uri, FutureTask<RequestContext>>>();

    try {
        for (Uri resourceUri : concatUri.getBatch()) {
            try {
                HttpRequest httpReq = concatUri.makeHttpRequest(resourceUri);
                FutureTask<RequestContext> httpFetcher = new FutureTask<RequestContext>(
                        new HttpFetchCallable(httpReq));
                futureTasks.add(Pair.of(httpReq.getUri(), httpFetcher));
                executor.execute(httpFetcher);
            } catch (GadgetException ge) {
                if (cos.outputError(resourceUri, ge)) {
                    // True returned from outputError indicates a terminal error.
                    return false;
                }
            }
        }

        for (Pair<Uri, FutureTask<RequestContext>> futureTask : futureTasks) {
            RequestContext requestCxt = null;
            try {
                try {
                    requestCxt = futureTask.two.get();
                } catch (InterruptedException ie) {
                    throw new GadgetException(GadgetException.Code.INTERNAL_SERVER_ERROR, ie);
                } catch (ExecutionException ee) {
                    throw new GadgetException(GadgetException.Code.INTERNAL_SERVER_ERROR, ee);
                }
                if (requestCxt.getGadgetException() != null) {
                    throw requestCxt.getGadgetException();
                }
                HttpResponse httpResp = requestCxt.getHttpResp();
                if (httpResp != null) {
                    if (contentRewriterRegistry != null) {
                        try {
                            httpResp = contentRewriterRegistry.rewriteHttpResponse(requestCxt.getHttpReq(),
                                    httpResp);
                        } catch (RewritingException e) {
                            throw new GadgetException(GadgetException.Code.INTERNAL_SERVER_ERROR, e,
                                    e.getHttpStatusCode());
                        }
                    }
                    cos.output(futureTask.one, httpResp);
                } else {
                    return false;
                }
            } catch (GadgetException ge) {
                if (cos.outputError(futureTask.one, ge)) {
                    return false;
                }
            }
        }
    } finally {
        if (cos != null) {
            try {
                cos.close();
            } catch (IOException ioe) {
                // Ignore
            }
        }
    }

    return true;
}

From source file:net.sourceforge.pmd.docs.DeadLinksChecker.java

public void checkDeadLinks(Path rootDirectory) {
    final Path pagesDirectory = rootDirectory.resolve("docs/pages");

    if (!Files.isDirectory(pagesDirectory)) {
        LOG.warning("can't check for dead links, didn't find \"pages\" directory at: " + pagesDirectory);
        System.exit(1);//from w ww .  java 2  s  .  com
    }

    // read all .md-files in the pages directory
    final List<Path> mdFiles = listMdFiles(pagesDirectory);

    // Stores file path to the future deadlinks. If a future evaluates to null, the link is not dead
    final Map<Path, List<Future<String>>> fileToDeadLinks = new HashMap<>();
    // make a list of all valid link targets
    final Set<String> htmlPages = extractLinkTargets(mdFiles);

    // scan all .md-files for dead local links
    int scannedFiles = 0;
    int foundExternalLinks = 0;
    int checkedExternalLinks = 0;

    for (Path mdFile : mdFiles) {
        final String pageContent = fileToString(mdFile);
        scannedFiles++;

        // iterate line-by-line for better reporting the line numbers
        final String[] lines = pageContent.split("\r?\n");
        for (int index = 0; index < lines.length; index++) {
            final String line = lines[index];
            final int lineNo = index + 1;

            final Matcher matcher = LOCAL_LINK_PATTERN.matcher(line);
            linkCheck: while (matcher.find()) {
                final String linkText = matcher.group();
                final String linkTarget = matcher.group(1).replaceAll("^/+", ""); // remove the leading "/"
                boolean linkOk;

                if (linkTarget.startsWith(LOCAL_FILE_PREFIX)) {
                    String localLinkPart = linkTarget.substring(LOCAL_FILE_PREFIX.length());
                    if (localLinkPart.contains("#")) {
                        localLinkPart = localLinkPart.substring(0, localLinkPart.indexOf('#'));
                    }

                    final Path localFile = rootDirectory.resolve(localLinkPart);
                    linkOk = Files.isRegularFile(localFile);
                    if (!linkOk) {
                        LOG.warning("local file not found: " + localFile);
                        LOG.warning("  linked by: " + linkTarget);
                    }

                } else if (linkTarget.startsWith("http://") || linkTarget.startsWith("https://")) {
                    foundExternalLinks++;

                    if (!CHECK_EXTERNAL_LINKS) {
                        LOG.finer("ignoring check of external url: " + linkTarget);
                        continue;
                    }

                    for (String ignoredUrlPrefix : IGNORED_URL_PREFIXES) {
                        if (linkTarget.startsWith(ignoredUrlPrefix)) {
                            LOG.finer("not checking link: " + linkTarget);
                            continue linkCheck;
                        }
                    }

                    checkedExternalLinks++;
                    linkOk = true;

                    Future<String> futureMessage = getCachedFutureResponse(linkTarget).thenApply(c -> c >= 400)
                            // It's important not to use the matcher in this mapper!
                            // It may be exhausted at the time of execution
                            .thenApply(dead -> dead ? String.format("%8d: %s", lineNo, linkText) : null);

                    addDeadLink(fileToDeadLinks, mdFile, futureMessage);

                } else {
                    // ignore local anchors
                    if (linkTarget.startsWith("#")) {
                        continue;
                    }

                    // ignore some pages where automatic link detection doesn't work
                    if (EXCLUDED_LINK_TARGETS.matcher(linkTarget).matches()) {
                        continue;
                    }

                    linkOk = linkTarget.isEmpty() || htmlPages.contains(linkTarget);
                }

                if (!linkOk) {
                    addDeadLink(fileToDeadLinks, mdFile,
                            new FutureTask<>(() -> String.format("%8d: %s", lineNo, linkText)));
                }
            }
        }
    }

    executorService.shutdown();

    LOG.info("Scanned " + scannedFiles + " files for dead links.");
    LOG.info("  Found " + foundExternalLinks + " external links, " + checkedExternalLinks
            + " of those where checked.");

    if (!CHECK_EXTERNAL_LINKS) {
        LOG.info("External links weren't checked, set -D" + CHECK_EXTERNAL_LINKS_PROPERTY
                + "=true to enable it.");
    }

    Map<Path, List<String>> joined = joinFutures(fileToDeadLinks);

    if (joined.isEmpty()) {
        LOG.info("No errors found!");
    } else {
        LOG.warning("Found dead link(s):");
        for (Path file : joined.keySet()) {
            System.err.println(rootDirectory.relativize(file).toString());
            joined.get(file).forEach(LOG::warning);
        }
        throw new AssertionError("Dead links detected");
    }
}

From source file:com.alibaba.napoli.metamorphosis.client.consumer.ConsumerZooKeeper.java

/**
 * /*from  www  . ja  va2  s .co  m*/
 * 
 * @throws Exception
 */
public void registerConsumer(final ConsumerConfig consumerConfig, final FetchManager fetchManager,
        final ConcurrentHashMap<String/* topic */, SubscriberInfo> topicSubcriberRegistry,
        final OffsetStorage offsetStorage, final LoadBalanceStrategy loadBalanceStrategy) throws Exception {

    final FutureTask<ZKLoadRebalanceListener> task = new FutureTask<ZKLoadRebalanceListener>(
            new Callable<ZKLoadRebalanceListener>() {

                @Override
                public ZKLoadRebalanceListener call() throws Exception {
                    final ZKGroupDirs dirs = ConsumerZooKeeper.this.metaZookeeper.new ZKGroupDirs(
                            consumerConfig.getGroup());
                    final String consumerUUID = ConsumerZooKeeper.this.getConsumerUUID(consumerConfig);
                    final String consumerUUIDString = consumerConfig.getGroup() + "_" + consumerUUID;
                    final ZKLoadRebalanceListener loadBalanceListener = new ZKLoadRebalanceListener(
                            fetchManager, dirs, consumerUUIDString, consumerConfig, offsetStorage,
                            topicSubcriberRegistry, loadBalanceStrategy);
                    return ConsumerZooKeeper.this.registerConsumerInternal(loadBalanceListener);
                }

            });
    final FutureTask<ZKLoadRebalanceListener> existsTask = this.consumerLoadBalanceListeners
            .putIfAbsent(fetchManager, task);
    if (existsTask == null) {
        task.run();
    } else {
        throw new MetaClientException("Consumer has been already registed");
    }

}