Example usage for java.util.concurrent TimeUnit MINUTES

List of usage examples for java.util.concurrent TimeUnit MINUTES

Introduction

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

Prototype

TimeUnit MINUTES

To view the source code for java.util.concurrent TimeUnit MINUTES.

Click Source Link

Document

Time unit representing sixty seconds.

Usage

From source file:learn.jersey.services.MultiThreadedClientExample.java

@Override
public int run(String[] args) throws Exception {

    if (args.length < 1 || args.length > 2) {
        System.out.println("Usage: " + this.getClass().getName() + " tableName [num_operations]");
        return -1;
    }/*from   w  ww . j ava2 s.  co m*/

    final TableName tableName = TableName.valueOf(args[0]);
    int numOperations = DEFAULT_NUM_OPERATIONS;

    // the second arg is the number of operations to send.
    if (args.length == 2) {
        numOperations = Integer.parseInt(args[1]);
    }

    // Threads for the client only.
    //
    // We don't want to mix hbase and business logic.
    //
    ExecutorService service = new ForkJoinPool(threads * 2);

    // Create two different connections showing how it's possible to
    // separate different types of requests onto different connections
    final Connection writeConnection = ConnectionFactory.createConnection(getConf(), service);
    final Connection readConnection = ConnectionFactory.createConnection(getConf(), service);

    // At this point the entire cache for the region locations is full.
    // Only do this if the number of regions in a table is easy to fit into
    // memory.
    //
    // If you are interacting with more than 25k regions on a client then
    // it's probably not good
    // to do this at all.
    warmUpConnectionCache(readConnection, tableName);
    warmUpConnectionCache(writeConnection, tableName);

    List<Future<Boolean>> futures = new ArrayList<>(numOperations);
    for (int i = 0; i < numOperations; i++) {
        double r = ThreadLocalRandom.current().nextDouble();
        Future<Boolean> f;

        // For the sake of generating some synthetic load this queues
        // some different callables.
        // These callables are meant to represent real work done by your
        // application.
        if (r < .30) {
            f = internalPool.submit(new WriteExampleCallable(writeConnection, tableName));
        } else if (r < .50) {
            f = internalPool.submit(new SingleWriteExampleCallable(writeConnection, tableName));
        } else {
            f = internalPool.submit(new ReadExampleCallable(writeConnection, tableName));
        }
        futures.add(f);
    }

    // Wait a long time for all the reads/writes to complete
    for (Future<Boolean> f : futures) {
        f.get(10, TimeUnit.MINUTES);
    }

    // Clean up after our selves for cleanliness
    internalPool.shutdownNow();
    service.shutdownNow();
    return 0;
}

From source file:io.druid.query.lookup.LookupReferencesManager.java

@LifecycleStart
public void start() {
    if (!lifecycleLock.canStart()) {
        throw new ISE("can't start.");
    }//from   w  w  w  .j a  v a2s  .c  o m
    try {
        LOG.info("LookupReferencesManager is starting.");
        loadAllLookupsAndInitStateRef();
        if (!testMode) {
            mainThread = Execs.makeThread("LookupReferencesManager-MainThread", () -> {
                try {
                    if (!lifecycleLock.awaitStarted()) {
                        LOG.error("WTF! lifecycle not started, lookup update notices will not be handled.");
                        return;
                    }

                    while (!Thread.interrupted() && lifecycleLock.awaitStarted(1, TimeUnit.MILLISECONDS)) {
                        try {
                            handlePendingNotices();
                            LockSupport.parkNanos(LookupReferencesManager.this, TimeUnit.MINUTES.toNanos(1));
                        } catch (Throwable t) {
                            LOG.makeAlert(t, "Error occured while lookup notice handling.").emit();
                        }
                    }
                } catch (Throwable t) {
                    LOG.error(t,
                            "Error while waiting for lifecycle start. lookup updates notices will not be handled");
                } finally {
                    LOG.info("Lookup Management loop exited, Lookup notices are not handled anymore.");
                }
            }, true);

            mainThread.start();
        }

        LOG.info("LookupReferencesManager is started.");
        lifecycleLock.started();
    } finally {
        lifecycleLock.exitStart();
    }
}

From source file:com.falcon.orca.handlers.StandAloneHandler.java

@Override
public void handle() {
    BufferedReader br = new BufferedReader(new InputStreamReader(System.in, StandardCharsets.UTF_8));
    Options options = createOptions();/*from www.j  a v  a 2  s . c  o  m*/
    printOnCmd("Welcome to ORCA type --help | -h  to see what ORCA can do.");
    try {
        String command = br.readLine();
        while (command != null) {
            if (!StringUtils.isEmpty(command)) {
                try {
                    String[] treatedCommandParts = treatCommands(command);
                    commandLine = commandLineParser.parse(options, treatedCommandParts);
                    if (commandLine.hasOption("start")) {
                        if (manager != null && !manager.isTerminated()) {
                            printOnCmd("Already running a job, please wait!!");
                        } else {
                            RunDetails runDetails = createRunDetails(commandLine);
                            if (runDetails.isBodyDynamic() || runDetails.isUrlDynamic()) {
                                DataReader dataReader = new JsonFileReader(runDetails.getDataFilePath(),
                                        runDetails.getTemplateFilePath());
                                HashMap<String, HashMap<String, List<Object>>> dynDataFromFile = dataReader
                                        .readVariableValues();
                                HashMap<String, HashMap<String, DynVarUseType>> dynVarUseTypeFromFile = dataReader
                                        .readVariableUseType();
                                HashMap<String, List<Object>> bodyParams = null;
                                String template = null;
                                HashMap<String, DynVarUseType> bodyParamsUseType = null;
                                HashMap<String, List<Object>> urlParams = null;
                                HashMap<String, DynVarUseType> urlParamsUseType = null;
                                if (runDetails.isBodyDynamic()) {
                                    bodyParams = dynDataFromFile.get("bodyData");
                                    template = dataReader.readTemplate();
                                    bodyParamsUseType = dynVarUseTypeFromFile.get("bodyVarUseType");
                                }
                                if (runDetails.isUrlDynamic()) {
                                    urlParams = dynDataFromFile.get("urlData");
                                    urlParamsUseType = dynVarUseTypeFromFile.get("urlVarUseType");
                                }
                                HashMap<String, DynGenerator> generators = dataReader.readGenerators();
                                DynDataStore dataStore = new DynDataStore(bodyParams, urlParams,
                                        bodyParamsUseType, urlParamsUseType, generators, template,
                                        runDetails.getUrl());
                                manager = actorSystem.actorOf(Manager.props(runDetails, dataStore));
                            } else {
                                manager = actorSystem.actorOf(Manager.props(runDetails, null));
                            }
                            ManagerCommand managerCommand = new ManagerCommand();
                            managerCommand.setType(ManagerCommandType.START);
                            manager.tell(managerCommand, manager);
                        }
                    } else if (commandLine.hasOption("stop")) {
                        if (manager != null && !manager.isTerminated()) {
                            ManagerCommand managerCommand = new ManagerCommand();
                            managerCommand.setType(ManagerCommandType.STOP);
                            manager.tell(managerCommand, manager);
                            printOnCmd("Job killed successfully.");
                        } else {
                            printOnCmd("No job running.");
                        }
                    } else if (commandLine.hasOption("exit")) {
                        if (manager != null && !manager.isTerminated()) {
                            ManagerCommand managerCommand = new ManagerCommand();
                            managerCommand.setType(ManagerCommandType.STOP);
                            manager.tell(managerCommand, manager);
                        }
                        printOnCmd("Exiting the system gracefully now.");
                        actorSystem.shutdown();
                        actorSystem.awaitTermination(new FiniteDuration(1, TimeUnit.MINUTES));
                        break;
                    } else if (commandLine.hasOption("pause")) {
                        if (manager != null && !manager.isTerminated()) {
                            ManagerCommand managerCommand = new ManagerCommand();
                            managerCommand.setType(ManagerCommandType.PAUSE);
                            manager.tell(managerCommand, manager);
                        } else {
                            printOnCmd("No active jobs to pause.");
                        }
                    } else if (commandLine.hasOption("resume")) {
                        if (manager != null && !manager.isTerminated()) {
                            ManagerCommand managerCommand = new ManagerCommand();
                            managerCommand.setType(ManagerCommandType.RESUME);
                            manager.tell(managerCommand, manager);
                        } else {
                            printOnCmd("No paused job to resume.");
                        }
                    } else {
                        printOnCmd(printHelpStandAloneMode());
                    }
                } catch (ParseException pe) {
                    printOnCmd(printHelpStandAloneMode());
                } catch (MalformedURLException me) {
                    me.printStackTrace();
                }
            } else {
                printOnCmd("", false);
            }
            command = br.readLine();
        }
    } catch (IOException e) {
        printOnCmd("Something went wrong in reading input, please try again.");
    }
}

From source file:com.ikon.util.ExecutionUtils.java

/**
 * Execute command line//ww  w.ja  va2  s.c o  m
 */
public static ExecutionResult runCmd(String cmd[]) throws SecurityException, InterruptedException, IOException {
    log.debug("runCmd({})", Arrays.toString(cmd));
    return runCmdImpl(cmd, TimeUnit.MINUTES.toMillis(Config.SYSTEM_EXECUTION_TIMEOUT));
}

From source file:com.blacklocus.jres.request.index.JresUpdateDocumentTest.java

@Test(expected = ExecutionException.class)
public void testRetryOnConflictExpectError() throws InterruptedException, ExecutionException {
    final String index = "JresUpdateDocumentTest.testRetryOnConflictExpectError".toLowerCase();
    final String type = "test";
    final String id = "warzone";

    final AtomicReference<String> error = new AtomicReference<String>();
    final int numThreads = 16, numIterations = 100;

    ExecutorService x = Executors.newFixedThreadPool(numThreads);
    List<Future<?>> futures = new ArrayList<Future<?>>(numThreads);
    for (int i = 0; i < numThreads; i++) {
        futures.add(x.submit(new Callable<Void>() {
            @Override/*  w w  w.  j  a  va2  s.  c  o  m*/
            public Void call() throws Exception {
                for (int j = 0; j < numIterations; j++) {
                    jres.quest(new JresUpdateDocument(index, type, id, ImmutableMap.of("value", 0)));
                }
                return null;
            }
        }));
    }
    x.shutdown();
    x.awaitTermination(1, TimeUnit.MINUTES);

    for (Future<?> future : futures) {
        // expecting a conflict exception from ElasticSearch
        future.get();
    }
}

From source file:com.openkm.servlet.RepositoryStartupServlet.java

/**
 * Start OpenKM and possible repository and database initialization
 *///from  w w w . j  ava2s  .c  o  m
public static synchronized void start() throws ServletException {
    SystemAuthentication systemAuth = new SystemAuthentication();

    if (running) {
        throw new IllegalStateException("OpenKM already started");
    }

    try {
        log.info("*** Repository initializing... ***");

        if (Config.REPOSITORY_NATIVE) {
            systemAuth.enable();
            DbRepositoryModule.initialize();
            systemAuth.disable();
        } else {
            JcrRepositoryModule.initialize();
        }

        log.info("*** Repository initialized ***");
    } catch (Exception e) {
        throw new ServletException(e.getMessage(), e);
    }

    log.info("*** User database initialized ***");

    if (!Config.REPOSITORY_NATIVE) {
        // Test for datastore
        SessionImpl si = (SessionImpl) JcrRepositoryModule.getSystemSession();

        if (((RepositoryImpl) si.getRepository()).getDataStore() == null) {
            hasConfiguredDataStore = false;
        } else {
            hasConfiguredDataStore = true;
        }
    }

    // Create timers
    uiTimer = new Timer("Update Info", true);
    cronTimer = new Timer("Crontab Manager", true);
    uinTimer = new Timer("User Interface Notification", true);

    // Workflow
    log.info("*** Initializing workflow engine... ***");
    JbpmContext jbpmContext = JBPMUtils.getConfig().createJbpmContext();
    jbpmContext.setSessionFactory(HibernateUtil.getSessionFactory());
    jbpmContext.getGraphSession();
    jbpmContext.getJbpmConfiguration().getJobExecutor().start(); // startJobExecutor();
    jbpmContext.close();

    // Mime types
    log.info("*** Initializing MIME types... ***");
    MimeTypeConfig.loadMimeTypes();

    log.info("*** Activating update info ***");
    ui = new UpdateInfo();
    uiTimer.schedule(ui, TimeUnit.MINUTES.toMillis(5), TimeUnit.HOURS.toMillis(24)); // First in 5 min, next each 24 hours

    log.info("*** Activating cron ***");
    cron = new Cron();
    Calendar calCron = Calendar.getInstance();
    calCron.add(Calendar.MINUTE, 1);
    calCron.set(Calendar.SECOND, 0);
    calCron.set(Calendar.MILLISECOND, 0);

    // Round begin to next minute, 0 seconds, 0 miliseconds
    cronTimer.scheduleAtFixedRate(cron, calCron.getTime(), 60 * 1000); // First in 1 min, next each 1 min

    log.info("*** Activating UI Notification ***");
    uin = new UINotification();

    // First in 1 second next in x minutes
    uinTimer.scheduleAtFixedRate(uin, 1000, TimeUnit.MINUTES.toMillis(Config.SCHEDULE_UI_NOTIFICATION));

    try {
        // General maintenance works
        String dapContent = "com.openkm.dao.DashboardActivityDAO.purge();";
        CronTabUtils.createOrUpdate("Dashboard Activity Purge", "@daily", dapContent);

        String uisContent = "com.openkm.cache.UserItemsManager.serialize();";
        CronTabUtils.createOrUpdate("User Items Serialize", "@hourly", uisContent);

        String ruiContent = "com.openkm.cache.UserItemsManager.refreshDbUserItems();";
        CronTabUtils.createOrUpdate("Refresh User Items", "@weekly", ruiContent);

        String umiContent = "new com.openkm.core.UserMailImporter().run();";
        CronTabUtils.createOrUpdate("User Mail Importer", "*/30 * * * *", umiContent);

        String tewContent = "new com.openkm.extractor.TextExtractorWorker().run();";
        CronTabUtils.createOrUpdate("Text Extractor Worker", "*/5 * * * *", tewContent);

        String swdContent = "new com.openkm.core.Watchdog().run();";
        CronTabUtils.createOrUpdate("Session Watchdog", "*/5 * * * *", swdContent);

        String pptContent = "new com.openkm.util.pendtask.PendingTaskExecutor().run();";
        CronTabUtils.createOrUpdate("Process Pending Tasks", "*/5 * * * *", pptContent);

        // Datastore garbage collection
        if (!Config.REPOSITORY_NATIVE && hasConfiguredDataStore) {
            String dgcContent = "new com.openkm.module.jcr.stuff.DataStoreGarbageCollector().run();";
            CronTabUtils.createOrUpdate("Datastore Garbage Collector", "@daily", dgcContent);
        }
    } catch (Exception e) {
        log.warn(e.getMessage(), e);
    }

    try {
        log.info("*** Activating thesaurus repository ***");
        RDFREpository.getInstance();
    } catch (Exception e) {
        log.warn(e.getMessage(), e);
    }

    try {
        if (Config.REMOTE_CONVERSION_SERVER.equals("")) {
            if (!Config.SYSTEM_OPENOFFICE_PATH.equals("")) {
                log.info("*** Start OpenOffice manager ***");
                DocConverter.getInstance().start();
            } else if (!Config.SYSTEM_OPENOFFICE_SERVER.equals("")) {
                log.info("*** Using OpenOffice conversion server ***");
            } else {
                log.warn("*** No OpenOffice manager nor server configured ***");
            }
        } else {
            log.info("*** Remote conversion configured ***");
        }
    } catch (Throwable e) {
        log.warn(e.getMessage(), e);
    }

    // Initialize plugin framework
    ExtensionManager.getInstance();

    try {
        log.info("*** Execute start script ***");
        File script = new File(Config.HOME_DIR + File.separatorChar + Config.START_SCRIPT);
        ExecutionUtils.runScript(script);
        File jar = new File(Config.HOME_DIR + File.separatorChar + Config.START_JAR);
        ExecutionUtils.getInstance().runJar(jar);
    } catch (Throwable e) {
        log.warn(e.getMessage(), e);
    }

    try {
        log.info("*** Execute start SQL ***");
        File sql = new File(Config.HOME_DIR + File.separatorChar + Config.START_SQL);

        if (sql.exists() && sql.canRead()) {
            FileReader fr = new FileReader(sql);
            HibernateUtil.executeSentences(fr);
            IOUtils.closeQuietly(fr);
        } else {
            log.warn("Unable to read sql: {}", sql.getPath());
        }
    } catch (Throwable e) {
        log.warn(e.getMessage(), e);
    }

    // OpenKM is started
    running = true;
}

From source file:org.italiangrid.storm.webdav.server.WebDAVServer.java

private void setupMetricsReporting() {

    final StormMetricsReporter reporter = StormMetricsReporter.forRegistry(metricRegistry).build();

    reporter.start(1, TimeUnit.MINUTES);

}

From source file:fr.immotronic.ubikit.pems.enocean.impl.PairingManagerImpl.java

public PairingManagerImpl(DeviceManager deviceManager,
        /*LicenseManager licenseManager,*/ EventGate eventGateToHigherAbstractionModelLevels,
        ScheduledExecutorService executorService, String pemUID) {
    pairingMode = false;//from  www.  ja va 2 s.  c  o  m
    this.pemUID = pemUID;
    toPair = Collections.synchronizedMap(new HashMap<String, PairingEntry>());
    executorService.scheduleAtFixedRate(new CleaningThread(), CLEANING_THREAD_SLEEPING_PERIOD,
            CLEANING_THREAD_SLEEPING_PERIOD, TimeUnit.MINUTES);

    this.deviceManager = deviceManager;
    //this.licenseManager = licenseManager;
    this.eventGateToHigherAbstractionModelLevels = eventGateToHigherAbstractionModelLevels;
    eventGateToHigherAbstractionModelLevels.addListener(this);
}

From source file:backup.integration.MiniClusterTestBase.java

@Test
public void testIntegrationBasic() throws Exception {
    File hdfsDir = setupHdfsLocalDir();
    Configuration conf = setupConfig(hdfsDir);

    MiniDFSCluster hdfsCluster = new MiniDFSCluster.Builder(conf).build();
    Thread thread = null;//from  ww w .  j a  v a2 s  .c  om
    try {
        DistributedFileSystem fileSystem = hdfsCluster.getFileSystem();
        Path path = new Path("/testing.txt");
        writeFile(fileSystem, path);
        Thread.sleep(TimeUnit.SECONDS.toMillis(5));
        AtomicBoolean success = new AtomicBoolean(false);
        thread = new Thread(new Runnable() {
            @Override
            public void run() {
                boolean beginTest = true;
                while (true) {
                    try {
                        try (ByteArrayOutputStream output = new ByteArrayOutputStream()) {
                            try (FSDataInputStream inputStream = fileSystem.open(path)) {
                                IOUtils.copy(inputStream, output);
                            }
                            if (beginTest) {
                                hdfsCluster.startDataNodes(conf, 1, true, null, null);
                                hdfsCluster.stopDataNode(0);
                                beginTest = false;
                            } else {
                                LOG.info("Missing block restored.");
                                success.set(true);
                                return;
                            }
                        }
                    } catch (IOException e) {
                        LOG.error(e.getMessage());
                    }
                    try {
                        Thread.sleep(1000);
                    } catch (InterruptedException e) {
                        return;
                    }
                }
            }
        });
        thread.start();
        thread.join(TimeUnit.MINUTES.toMillis(2));
        if (!success.get()) {
            fail();
        }
    } finally {
        if (thread != null) {
            thread.interrupt();
        }
        hdfsCluster.shutdown();
        destroyBackupStore(conf);
    }
}