Example usage for java.util.concurrent Executors newSingleThreadScheduledExecutor

List of usage examples for java.util.concurrent Executors newSingleThreadScheduledExecutor

Introduction

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

Prototype

public static ScheduledExecutorService newSingleThreadScheduledExecutor() 

Source Link

Document

Creates a single-threaded executor that can schedule commands to run after a given delay, or to execute periodically.

Usage

From source file:org.codice.ddf.spatial.ogc.csw.catalog.source.CswSource.java

/**
 * Instantiates a CswSource. This constructor is for unit tests
 *
 * @param remoteCsw The JAXRS connection to a {@link org.codice.ddf.spatial.ogc.csw.catalog.common.Csw}
 * @param context   The {@link BundleContext} from the OSGi Framework
 *//*  w ww  .j a  v a 2 s. co m*/
public CswSource(RemoteCsw remoteCsw, BundleContext context, CswSourceConfiguration cswSourceConfiguration,
        CswTransformProvider provider) {
    this.remoteCsw = remoteCsw;
    this.context = context;
    this.cswSourceConfiguration = cswSourceConfiguration;
    this.cswTransformProvider = provider;
    scheduler = Executors.newSingleThreadScheduledExecutor();
}

From source file:org.codice.ddf.spatial.ogc.csw.catalog.source.CswSource.java

/**
 * Instantiates a CswSource.
 */
public CswSource() {
    cswSourceConfiguration = new CswSourceConfiguration();
    scheduler = Executors.newSingleThreadScheduledExecutor();
}

From source file:at.wada811.android.library.demos.concurrent.ExecutorActivity.java

/**
 * {@link ScheduledExecutorService#scheduleWithFixedDelay(Runnable, long, long, TimeUnit)}
 * ???//from   w  w  w .  ja va 2s. c  om
 * 
 * <p>
 * ?????????????????????? <br>
 * ????????????????????
 * </p>
 */
public void newSingleThreadScheduledExecutorWithFixedDelayDuringExecutionTest() {
    LogUtils.d();
    ScheduledExecutorService executorService = Executors.newSingleThreadScheduledExecutor();
    executorService.scheduleWithFixedDelay(new ExecutorRunnable("A", 3), 1, 2, TimeUnit.SECONDS);
    shutdown(executorService);
}

From source file:org.apache.solr.client.solrj.impl.LBHttpSolrServer.java

private void startAliveCheckExecutor() {
    if (aliveCheckExecutor == null) {
        synchronized (this) {
            if (aliveCheckExecutor == null) {
                aliveCheckExecutor = Executors.newSingleThreadScheduledExecutor();
                aliveCheckExecutor.scheduleAtFixedRate(
                        getAliveCheckRunner(new WeakReference<LBHttpSolrServer>(this)), this.interval,
                        this.interval, TimeUnit.MILLISECONDS);
            }//from  ww w.  ja  v a2  s .  c o  m
        }
    }
}

From source file:net.firejack.platform.core.cache.CacheProcessor.java

public void scheduleReload(int initialDelay, int delay, TimeUnit timeUnit) {
    executor = Executors.newSingleThreadScheduledExecutor();
    executor.scheduleWithFixedDelay(new Runnable() {
        @Override//from w  w  w  . j av a 2  s .c  o  m
        public void run() {
            loadData(true);
        }
    }, initialDelay, delay, timeUnit);
}

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

private void startHeartbeat() {
    final Session _this = this;

    this.heartbeatService = Executors.newSingleThreadScheduledExecutor();
    this.heartbeatService.scheduleAtFixedRate(new Runnable() {
        public void run() {
            if (Teak.isDebug) {
                Log.v(LOG_TAG, "Sending heartbeat for user: " + userId);
            }//from   w ww .java2  s. co m

            HttpsURLConnection connection = null;
            try {
                String queryString = "game_id=" + URLEncoder.encode(_this.appConfiguration.appId, "UTF-8")
                        + "&api_key=" + URLEncoder.encode(_this.userId, "UTF-8") + "&sdk_version="
                        + URLEncoder.encode(Teak.SDKVersion, "UTF-8") + "&sdk_platform="
                        + URLEncoder.encode(_this.deviceConfiguration.platformString, "UTF-8") + "&app_version="
                        + URLEncoder.encode(String.valueOf(_this.appConfiguration.appVersion), "UTF-8")
                        + (_this.countryCode == null ? ""
                                : "&country_code="
                                        + URLEncoder.encode(String.valueOf(_this.countryCode), "UTF-8"))
                        + "&buster=" + URLEncoder.encode(UUID.randomUUID().toString(), "UTF-8");
                URL url = new URL("https://iroko.gocarrot.com/ping?" + queryString);
                connection = (HttpsURLConnection) url.openConnection();
                connection.setRequestProperty("Accept-Charset", "UTF-8");
                connection.setUseCaches(false);

                int responseCode = connection.getResponseCode();
                if (Teak.isDebug) {
                    Log.v(LOG_TAG, "Heartbeat response code: " + responseCode);
                }
            } catch (Exception e) {
                Log.e(LOG_TAG, Log.getStackTraceString(e));
            } finally {
                if (connection != null) {
                    connection.disconnect();
                }
            }
        }
    }, 0, 1, TimeUnit.MINUTES); // TODO: If RemoteConfiguration specifies a different rate, use that
}

From source file:com.mucommander.ui.viewer.image.ImageViewer.java

private void fixMouseMovementEventsIssue() {
    if (mouseMovementIssueFixed) {
        return;//from w ww. j a va 2  s . c  o m
    }
    mouseMovementIssueFixed = true;
    Runnable task = new Runnable() {
        public void run() {
            try {
                int w = getFrame().getWidth();
                int h = getFrame().getHeight();
                getFrame().setSize(w, h - 1);
                getFrame().setSize(w, h);
            } catch (Exception e) {
            }
        }
    };
    Executors.newSingleThreadScheduledExecutor().schedule(task, 1000, TimeUnit.MILLISECONDS);
}

From source file:com.networknt.client.Client.java

private void checkCCTokenExpired() throws ClientException, ApiException {
    long tokenRenewBeforeExpired = (Integer) oauthConfig.get(TOKEN_RENEW_BEFORE_EXPIRED);
    long expiredRefreshRetryDelay = (Integer) oauthConfig.get(EXPIRED_REFRESH_RETRY_DELAY);
    long earlyRefreshRetryDelay = (Integer) oauthConfig.get(EARLY_REFRESH_RETRY_DELAY);
    boolean isInRenewWindow = expire - System.currentTimeMillis() < tokenRenewBeforeExpired;
    logger.trace("isInRenewWindow = " + isInRenewWindow);
    if (isInRenewWindow) {
        if (expire <= System.currentTimeMillis()) {
            logger.trace("In renew window and token is expired.");
            // block other request here to prevent using expired token.
            synchronized (Client.class) {
                if (expire <= System.currentTimeMillis()) {
                    logger.trace("Within the synch block, check if the current request need to renew token");
                    if (!renewing || System.currentTimeMillis() > expiredRetryTimeout) {
                        // if there is no other request is renewing or the renewing flag is true but renewTimeout is passed
                        renewing = true;
                        expiredRetryTimeout = System.currentTimeMillis() + expiredRefreshRetryDelay;
                        logger.trace(//from w  w  w.  ja va 2  s .com
                                "Current request is renewing token synchronously as token is expired already");
                        getCCToken();
                        renewing = false;
                    } else {
                        logger.trace("Circuit breaker is tripped and not timeout yet!");
                        // reject all waiting requests by thrown an exception.
                        throw new ApiException(new Status(STATUS_CLIENT_CREDENTIALS_TOKEN_NOT_AVAILABLE));
                    }
                }
            }
        } else {
            // Not expired yet, try to renew async but let requests use the old token.
            logger.trace("In renew window but token is not expired yet.");
            synchronized (Client.class) {
                if (expire > System.currentTimeMillis()) {
                    if (!renewing || System.currentTimeMillis() > earlyRetryTimeout) {
                        renewing = true;
                        earlyRetryTimeout = System.currentTimeMillis() + earlyRefreshRetryDelay;
                        logger.trace("Retrieve token async is called while token is not expired yet");

                        ScheduledExecutorService executor = Executors.newSingleThreadScheduledExecutor();

                        executor.schedule(new Runnable() {
                            @Override
                            public void run() {
                                try {
                                    getCCToken();
                                    renewing = false;
                                    logger.trace("Async get token is completed.");
                                } catch (Exception e) {
                                    logger.error("Async retrieve token error", e);
                                    // swallow the exception here as it is on a best effort basis.
                                }
                            }
                        }, 50, TimeUnit.MILLISECONDS);
                        executor.shutdown();
                    }
                }
            }
        }
    }
    logger.trace("Check secondary token is done!");
}

From source file:org.tupelo_schneck.electric.ted.TedImporter.java

private ExecutorService repeatedlyImport(int count, boolean longImport, int interval) {
    ScheduledExecutorService execServ = Executors.newSingleThreadScheduledExecutor();
    execServ.scheduleAtFixedRate(new MultiImporter(count, longImport), 0, interval, TimeUnit.SECONDS);
    return execServ;
}

From source file:org.deri.iris.performance.IRISPerformanceTest.java

/**
 * Executes a set of datalog queries using the given configuration
 * @param queries The set of Datalog queries
 * @param config The configuration for the test suite
 * @return a list of IRISTestCase objects with the result of the test campaign
 *///from  w  ww .  j a v  a2 s . c om
public List<IRISTestCase> executeTests(final List<String> queries, final TestConfiguration config) {

    // Get the logger
    LOGGER = Logger.getLogger(IRISPerformanceTest.class.getName());

    // Construct a valid IRIS+- program using the queries and the configuration file
    String program = "";

    // add the query and its IRIS execution command to the program
    program += "/// Query ///\n";
    for (final String s : queries) {
        program += s + "\n";
        program += "?-" + s.substring(0, s.indexOf(":-")) + ".\n";
    }
    program += "\n";

    // If reasoning is enabled, add the TBOX to the program
    program += "/// TBox ///\n";
    if (config.getReasoning()) {
        String tboxPath = config.getTestHomePath() + "/" + config.getDataset() + "/tbox";
        if (config.getExpressiveness().compareTo("RDFS") == 0) {
            tboxPath += "/rdfs";
        }
        if (config.getExpressiveness().compareTo("OWL-QL") == 0) {
            tboxPath += "/owlql";
        }
        final String tbox = loadFile(tboxPath + "/" + config.getDataset() + ".dtg");
        program += tbox + "\n";
    } else {
        program += "/// EMPTY ///\n";
    }

    // Add the SBox
    program += "/// SBox ///\n";
    String sboxPath = config.getTestHomePath() + "/" + config.getDataset() + "/sbox";
    if (config.getExpressiveness().compareTo("RDFS") == 0) {
        sboxPath += "/rdfs";
    }
    if (config.getExpressiveness().compareTo("OWL-QL") == 0) {
        sboxPath += "/owlql";
    }
    final String sbox = loadFile(sboxPath + "/" + config.getDataset() + ".dtg");
    program += sbox + "\n\n";

    LOGGER.debug(program);

    // Get the parser
    final Parser parser = new Parser();

    // Parse the program
    try {
        parser.parse(program);
    } catch (final ParserException e) {
        e.printStackTrace();
    }

    // Get the TGDs from the set of rules
    final List<IRule> tgds = RewritingUtils.getTGDs(parser.getRules(), parser.getQueries());

    // Get the query bodies
    final List<IRule> bodies = new ArrayList<IRule>(parser.getRules());
    final List<IRule> datalogQueries = RewritingUtils.getQueries(bodies, parser.getQueries());

    // Get the constraints from the set of rules
    final Set<IRule> constraints = RewritingUtils.getConstraints(parser.getRules(), parser.getQueries());

    // Get the SBox rules from the set of rules
    final List<IRule> storageRules = RewritingUtils.getSBoxRules(parser.getRules(), parser.getQueries());

    // Check that the TBox is FO-reducible
    IRuleSafetyProcessor ruleProc = new LinearReducibleRuleSafetyProcessor();
    try {
        ruleProc.process(tgds);
    } catch (final RuleUnsafeException e) {
        e.printStackTrace();
    }

    // Check that the SBox rules are Safe Datalog
    ruleProc = new StandardRuleSafetyProcessor();
    try {
        ruleProc.process(storageRules);
    } catch (final RuleUnsafeException e) {
        e.printStackTrace();
    }

    // Connect to the storage
    StorageManager.getInstance();
    try {
        StorageManager.connect(config.getDBVendor(), config.getDBProtocol(), config.getDBHost(),
                config.getDBPort(), config.getDBName(), config.getSchemaName(), config.getDBUsername(),
                config.getDBPassword());
    } catch (final SQLException e) {
        e.printStackTrace();
    }

    // Evaluate the queries
    final List<IRISTestCase> output = new LinkedList<IRISTestCase>();
    for (final IQuery q : parser.getQueries()) {
        // Generate a new test-case
        final IRISTestCase currentTest = new IRISTestCase();
        int nTask = -10;

        // Get the Factories
        final IRelationFactory rf = new RelationFactory();

        // Get the Rewriter Engine
        final ParallelRewriter rewriter = new ParallelRewriter(DecompositionStrategy.DECOMPOSE,
                RewritingLanguage.UCQ, SubCheckStrategy.TAIL, NCCheck.TAIL);

        // Get and log the rule corresponding to the query
        final IRule ruleQuery = getRuleQuery(q, datalogQueries);
        currentTest.setQuery(ruleQuery);

        final Map<Pair<IPosition, IPosition>, Set<List<IRule>>> deps = DepGraphUtils
                .computePositionDependencyGraph(tgds);

        final Set<Expressivity> exprs = RewritingUtils.getExpressivity(tgds);

        // Compute and log the FO-Rewriting
        LOGGER.info("Computing TBox Rewriting");
        float duration = -System.nanoTime();
        final Set<IRule> rewriting = rewriter.getRewriting(ruleQuery, tgds, constraints, deps, exprs);
        duration = ((duration + System.nanoTime()) / 1000000);
        currentTest.getTasks()
                .add(new Task(nTask++, "TBox Rewriting", duration, 0, 0, "ms", rewriting.toString()));
        LOGGER.info("done.");
        int count = 0;
        for (final IRule r : rewriting) {
            LOGGER.debug("(Qr" + ++count + ")" + r);
        }

        // Produce the rewriting according to the Nyaya Data Model
        final IQueryRewriter ndmRewriter = new NDMRewriter(storageRules);

        // Create a buffer for the output
        final IRelation outRelation = rf.createRelation();

        // Get the SBox rewriting
        try {
            LOGGER.info("Computing SBox Rewriting");
            final Set<IRule> sboxRewriting = new LinkedHashSet<IRule>();
            duration = -System.nanoTime();
            for (final IRule pr : rewriting) {
                sboxRewriting.addAll(ndmRewriter.getRewriting(pr));
            }
            duration = ((duration + System.nanoTime()) / 1000000);
            currentTest.getTasks()
                    .add(new Task(nTask++, "SBox Rewriting", duration, 0, 0, "ms", sboxRewriting.toString()));
            LOGGER.info("done.");
            count = 0;
            for (final IRule n : sboxRewriting) {
                LOGGER.debug("(Qn" + ++count + ")" + n);
            }

            // Produce the SQL rewriting for each query in the program
            final SQLRewriter sqlRewriter = new SQLRewriter(sboxRewriting);

            // Get the SQL rewriting as Union of Conjunctive Queries (UCQ)
            LOGGER.info("Computing SQL Rewriting");
            duration = -System.nanoTime();
            final List<String> ucqSQLRewriting = new LinkedList<String>();
            ucqSQLRewriting.add(sqlRewriter.getUCQSQLRewriting("", 10000, 0));
            duration = ((duration + System.nanoTime()) / 1000000);
            currentTest.getTasks()
                    .add(new Task(nTask++, "SQL Rewriting", duration, 0, 0, "ms", ucqSQLRewriting.toString()));
            LOGGER.info("done.");
            count = 0;
            for (final String s : ucqSQLRewriting) {
                LOGGER.debug("(Qs" + ++count + ") " + s);
            }

            // Execute the UCQ
            LOGGER.info("Executing SQL");

            // float ansConstructOverall = 0;

            // The synchronized structure to store the output tuples
            final Set<ITuple> result = Collections.synchronizedSet(new HashSet<ITuple>());

            /*
             * Prepare a set of runnable objects representing each partial rewriting to be executed in parallel
             */
            final List<RunnableQuery> rql = new LinkedList<RunnableQuery>();
            for (final String cq : ucqSQLRewriting) {
                // Construct a Runnable Query
                rql.add(new RunnableQuery(cq, result, currentTest.getTasks()));
            }

            // Get an executor that allows a number of parallel threads equals to the number of available processors
            // ExecutorService queryExecutor =
            // Executors.newFixedThreadPool(Runtime.getRuntime().availableProcessors()*5);
            final ExecutorService queryExecutor = Executors.newSingleThreadScheduledExecutor();

            // Execute all the partial rewritings in parallel
            float ucqExecOverall = -System.nanoTime();
            for (final RunnableQuery rq : rql) {
                queryExecutor.execute(rq);
            }
            queryExecutor.shutdown();
            if (queryExecutor.awaitTermination(1, TimeUnit.DAYS)) {
                LOGGER.info("done.");
            } else
                throw new InterruptedException("Timeout Occured");
            ucqExecOverall = ((ucqExecOverall + System.nanoTime()) / 1000000);
            StorageManager.disconnect();

            // inizio aggiunta
            float minTime = System.nanoTime();
            float maxTime = 0;
            float avgTime = 0;
            int n = 0;
            for (final Task t : currentTest.getTasks()) {
                if (t.getName().contains("Execution")) {
                    avgTime += (t.getFinalTime() - t.getInitTime()) / 1000000;
                    n++;
                    if (t.getFinalTime() > maxTime) {
                        maxTime = t.getFinalTime();
                    }
                    if (t.getInitTime() < minTime) {
                        minTime = t.getInitTime();
                    }
                }
            }
            ucqExecOverall = (maxTime - minTime) / 1000000;
            // fine aggiunta

            currentTest.getTasks()
                    .add(new Task(nTask++, "UCQ Overall Execution Time", ucqExecOverall, 0, 0, "ms"));

            // inizio aggiunta
            avgTime = (avgTime / n);
            System.out.println(n);
            currentTest.getTasks().add(new Task(nTask++, "UCQ Average Execution Time", avgTime, 0, 0, "ms"));
            Collections.sort(currentTest.getTasks());
            // fine aggiunta

            for (final ITuple t : result) {
                outRelation.add(t);
            }

        } catch (final SQLException e) {
            e.printStackTrace();
        } catch (final EvaluationException e) {
            e.printStackTrace();
        } catch (final InterruptedException e) {
            e.printStackTrace();
        }
        currentTest.setAnswer(outRelation);
        output.add(currentTest);
    }
    return (output);
}