Example usage for java.util.concurrent TimeUnit MILLISECONDS

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

Introduction

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

Prototype

TimeUnit MILLISECONDS

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

Click Source Link

Document

Time unit representing one thousandth of a second.

Usage

From source file:Main.java

public static void main(String[] args) throws java.lang.Exception {
    String[] StartTimes = { "10:00", "7:00" };
    String[] EndTimes = { "12:00", "14:56" };
    for (int i = 0; i < StartTimes.length; i++) {
        if (StartTimes != null && StartTimes.length > 0 && EndTimes != null && EndTimes.length > 0) {
            SimpleDateFormat format = new SimpleDateFormat("HH:mm");
            Date date1 = format.parse(StartTimes[i]);
            Date date2 = format.parse(EndTimes[i]);
            long millis = date2.getTime() - date1.getTime();

            String hourminute = String.format("%02d:%02d", TimeUnit.MILLISECONDS.toHours(millis),
                    TimeUnit.MILLISECONDS.toMinutes(millis)
                            - TimeUnit.HOURS.toMinutes(TimeUnit.MILLISECONDS.toHours(millis)));
            System.out.println(hourminute);
        }//from   w  w w .  java2s.  co  m
    }
}

From source file:ReplaceWorker.java

public static void main(String[] args) {
    map.put("key", 1);
    Main test = new Main();
    ThreadPoolExecutor threadPool = new ThreadPoolExecutor(10, 10, 100, TimeUnit.MILLISECONDS,
            new ArrayBlockingQueue<>(1000));
    for (int i = 0; i < 100; i++) {
        threadPool.submit(new MergeWorker());
    }/*from  ww w  .j  av a2s .c  o m*/
    awaitTermination(threadPool);
    System.out.println(test.map.get("key"));

    map.put("key", 1);
    threadPool = new ThreadPoolExecutor(10, 10, 100, TimeUnit.MILLISECONDS, new ArrayBlockingQueue<>(1000));
    for (int i = 0; i < 100; i++) {
        threadPool.submit(new ReplaceWorker());
    }
    awaitTermination(threadPool);
    System.out.println(test.map.get("key"));
}

From source file:httpscheduler.HttpScheduler.java

/**
 * @param args the command line arguments
 * @throws java.lang.Exception//from www.  j ava  2 s .  com
 */

public static void main(String[] args) throws Exception {

    if (args.length != 2) {
        System.err.println("Invalid command line parameters for worker");
        System.exit(-1);
    }

    int fixedExecutorSize = 4;

    //Creating fixed size executor
    ThreadPoolExecutor taskCommExecutor = new ThreadPoolExecutor(fixedExecutorSize, fixedExecutorSize, 0L,
            TimeUnit.MILLISECONDS, new LinkedBlockingQueue<Runnable>());
    // Used for late binding
    JobMap jobMap = new JobMap();

    // Set port number
    int port = Integer.parseInt(args[0]);

    // Set worker mode
    String mode = args[1].substring(2);

    // Set up the HTTP protocol processor
    HttpProcessor httpproc = HttpProcessorBuilder.create().add(new ResponseDate())
            .add(new ResponseServer("Test/1.1")).add(new ResponseContent()).add(new ResponseConnControl())
            .build();

    // Set up request handlers
    UriHttpRequestHandlerMapper reqistry = new UriHttpRequestHandlerMapper();
    // Different handlers for late binding and generic cases
    if (mode.equals("late"))
        reqistry.register("*", new LateBindingRequestHandler(taskCommExecutor, jobMap));
    else
        reqistry.register("*", new GenericRequestHandler(taskCommExecutor, mode));

    // Set up the HTTP service
    HttpService httpService = new HttpService(httpproc, reqistry);

    SSLServerSocketFactory sf = null;

    // create a thread to listen for possible client available connections
    Thread t;
    if (mode.equals("late"))
        t = new LateBindingRequestListenerThread(port, httpService, sf);
    else
        t = new GenericRequestListenerThread(port, httpService, sf);
    System.out.println("Request Listener Thread created");
    t.setDaemon(false);
    t.start();

    // main thread should wait for the listener to exit before shutdown the
    // task executor pool
    t.join();

    // shutdown task executor pool and wait for any taskCommExecutor thread
    // still running
    taskCommExecutor.shutdown();
    while (!taskCommExecutor.isTerminated()) {
    }

    System.out.println("Finished all task communication executor threads");
    System.out.println("Finished all tasks");

}

From source file:example.browser.Browser.java

public static void main(String[] args) {
    String url = BROKER_URL;
    if (args.length > 0) {
        url = args[0].trim();//from   w ww  . ja  v  a  2  s  .c  om
    }
    ActiveMQConnectionFactory connectionFactory = new ActiveMQConnectionFactory("admin", "password", url);
    Connection connection = null;

    try {

        connection = connectionFactory.createConnection();
        connection.start();

        Session session = connection.createSession(NON_TRANSACTED, Session.AUTO_ACKNOWLEDGE);
        Queue destination = session.createQueue("test-queue");
        QueueBrowser browser = session.createBrowser(destination);
        Enumeration enumeration = browser.getEnumeration();

        while (enumeration.hasMoreElements()) {
            TextMessage message = (TextMessage) enumeration.nextElement();
            System.out.println("Browsing: " + message);
            TimeUnit.MILLISECONDS.sleep(DELAY);
        }

        session.close();

    } catch (Exception e) {
        System.out.println("Caught exception!");
    } finally {
        if (connection != null) {
            try {
                connection.close();
            } catch (JMSException e) {
                System.out.println("Could not close an open connection...");
            }
        }
    }
}

From source file:com.github.joshelser.dropwizard.metrics.hadoop.StandaloneExample.java

public static void main(String[] args) throws Exception {
    final MetricRegistry metrics = new MetricRegistry();

    final HadoopMetrics2Reporter metrics2Reporter = HadoopMetrics2Reporter.forRegistry(metrics).build(
            DefaultMetricsSystem.initialize("StandaloneTest"), // The application-level name
            "Test", // Component name
            "Test", // Component description
            "Test"); // Name for each metric record
    final ConsoleReporter consoleReporter = ConsoleReporter.forRegistry(metrics).build();

    MetricsSystem metrics2 = DefaultMetricsSystem.instance();
    // Writes to stdout without a filename configuration
    // Will be invoked every 10seconds by default
    FileSink sink = new FileSink();
    metrics2.register("filesink", "filesink", sink);
    sink.init(new SubsetConfiguration(null, null) {
        public String getString(String key) {
            if (key.equals("filename")) {
                return null;
            }/*from w w w  . ja  va  2 s . c o  m*/
            return super.getString(key);
        }
    });

    // How often should the dropwizard reporter be invoked
    metrics2Reporter.start(500, TimeUnit.MILLISECONDS);
    // How often will the dropwziard metrics be logged to the console
    consoleReporter.start(2, TimeUnit.SECONDS);

    generateMetrics(metrics, 5000, 25, TimeUnit.MILLISECONDS, metrics2Reporter, 10);
}

From source file:io.rhiot.spec.IoTSpec.java

public static void main(String[] args) throws Exception {

    CommandLineParser parser = new DefaultParser();

    Options options = new Options();
    options.addOption(Option.builder("c").longOpt(CONFIG).desc(
            "Location of the test configuration file. A default value is 'src/main/resources/test.yaml' for easy IDE testing")
            .hasArg().build());/*from ww  w.j av  a  2  s  .  c  o m*/

    options.addOption(Option.builder("i").longOpt(INSTANCE).desc("Instance of the test; A default value is 1")
            .hasArg().build());

    options.addOption(Option.builder("r").longOpt(REPORT)
            .desc("Location of the test report. A default value is 'target/report.csv'").hasArg().build());

    CommandLine line = parser.parse(options, args);
    ObjectMapper mapper = new ObjectMapper(new YAMLFactory());
    TestProfile test = mapper.readValue(new File(line.getOptionValue(CONFIG, "src/main/resources/test.yaml")),
            TestProfile.class);
    int instance = Integer.valueOf(line.getOptionValue(INSTANCE, "1"));
    test.setInstance(instance);
    String report = line.getOptionValue(REPORT, "target/report.csv");
    test.setReport(new CSVReport(report));

    LOG.info("Test '" + test.getName() + "' instance " + instance + " started");
    final List<Driver> drivers = test.getDrivers();
    ExecutorService executorService = Executors.newFixedThreadPool(drivers.size());
    List<Future<Void>> results = executorService.invokeAll(drivers, test.getDuration(), TimeUnit.MILLISECONDS);
    executorService.shutdownNow();
    executorService.awaitTermination(5, TimeUnit.SECONDS);

    results.forEach(result -> {
        try {
            result.get();
        } catch (ExecutionException execution) {
            LOG.warn("Exception running driver", execution);
        } catch (Exception interrupted) {
        }
    });

    drivers.forEach(driver -> {
        driver.stop();

        try {
            test.getReport().print(driver);
        } catch (Exception e) {
            LOG.warn("Failed to write reports for the driver " + driver);
        }
        LOG.debug("Driver " + driver);
        LOG.debug("\t " + driver.getResult());
    });
    test.getReport().close();

    LOG.info("Test '" + test.getName() + "' instance " + instance + " finished");

}

From source file:io.anserini.util.SearchTimeUtil.java

public static void main(String[] args) throws IOException, ParseException, ClassNotFoundException,
        NoSuchMethodException, InvocationTargetException, IllegalAccessException, InstantiationException {

    if (args.length != 1) {
        System.err.println("Usage: SearchTimeUtil <indexDir>");
        System.err.println("indexDir: index directory");
        System.exit(1);//  ww  w  . j  a  va2 s . c  om
    }

    String[] topics = { "topics.web.1-50.txt", "topics.web.51-100.txt", "topics.web.101-150.txt",
            "topics.web.151-200.txt", "topics.web.201-250.txt", "topics.web.251-300.txt" };

    SearchWebCollection searcher = new SearchWebCollection(args[0]);

    for (String topicFile : topics) {
        Path topicsFile = Paths.get("src/resources/topics-and-qrels/", topicFile);
        TopicReader tr = (TopicReader) Class.forName("io.anserini.search.query." + "Webxml" + "TopicReader")
                .getConstructor(Path.class).newInstance(topicsFile);
        SortedMap<Integer, String> queries = tr.read();
        for (int i = 1; i <= 3; i++) {
            final long start = System.nanoTime();
            String submissionFile = File.createTempFile(topicFile + "_" + i, ".tmp").getAbsolutePath();
            RerankerCascade cascade = new RerankerCascade();
            cascade.add(new IdentityReranker());
            searcher.search(queries, submissionFile, new BM25Similarity(0.9f, 0.4f), 1000, cascade);
            final long durationMillis = TimeUnit.MILLISECONDS.convert(System.nanoTime() - start,
                    TimeUnit.NANOSECONDS);
            System.out.println(topicFile + "_" + i + " search completed in "
                    + DurationFormatUtils.formatDuration(durationMillis, "mm:ss:SSS"));
        }
    }

    searcher.close();
}

From source file:org.eclipseplugins.impexeditor.http.ImpexHttpClient.java

public static void main(final String[] args) throws Exception {

    final ImpexHttpClient impexHttpClient = new ImpexHttpClient("http://localhost:9001/hac");
    final long startTime = System.currentTimeMillis();
    final Map<String, JsonArray> allatypes = new HashMap<String, JsonArray>();
    for (final JsonValue type : impexHttpClient.getAllTypes()) {
        allatypes.put(type.asString(),//  w ww  .ja v  a2  s  .  c  om
                impexHttpClient.getTypeandAttribute(type.asString()).get("attributes").asArray());
    }
    for (final String type : allatypes.keySet()) {
        System.out.println("type :" + type);
        for (final JsonValue string : allatypes.get(type)) {
            System.out.println("---- " + string.asString());
        }
    }
    final long stopTime = System.currentTimeMillis();
    final long elapsedTime = stopTime - startTime;
    System.out.println("Success elapsed time in seconde " + TimeUnit.MILLISECONDS.toSeconds(elapsedTime));
}

From source file:edu.mit.lib.mama.Mama.java

public static void main(String[] args) {

    Properties props = findConfig(args);
    DBI dbi = new DBI(props.getProperty("dburl"), props);
    // Advanced instrumentation/metrics if requested
    if (System.getenv("MAMA_DB_METRICS") != null) {
        dbi.setTimingCollector(new InstrumentedTimingCollector(metrics));
    }/*from www.  j ava 2  s .  co m*/
    // reassign default port 4567
    if (System.getenv("MAMA_SVC_PORT") != null) {
        port(Integer.valueOf(System.getenv("MAMA_SVC_PORT")));
    }
    // if API key given, use exception monitoring service
    if (System.getenv("HONEYBADGER_API_KEY") != null) {
        reporter = new HoneybadgerReporter();
    }

    get("/ping", (req, res) -> {
        res.type("text/plain");
        res.header("Cache-Control", "must-revalidate,no-cache,no-store");
        return "pong";
    });

    get("/metrics", (req, res) -> {
        res.type("application/json");
        res.header("Cache-Control", "must-revalidate,no-cache,no-store");
        ObjectMapper objectMapper = new ObjectMapper()
                .registerModule(new MetricsModule(TimeUnit.SECONDS, TimeUnit.MILLISECONDS, true));
        try (ServletOutputStream outputStream = res.raw().getOutputStream()) {
            objectMapper.writer().withDefaultPrettyPrinter().writeValue(outputStream, metrics);
        }
        return "";
    });

    get("/shutdown", (req, res) -> {
        boolean auth = false;
        try {
            if (!isNullOrEmpty(System.getenv("MAMA_SHUTDOWN_KEY")) && !isNullOrEmpty(req.queryParams("key"))
                    && System.getenv("MAMA_SHUTDOWN_KEY").equals(req.queryParams("key"))) {
                auth = true;
                return "Shutting down";
            } else {
                res.status(401);
                return "Not authorized";
            }
        } finally {
            if (auth) {
                stop();
            }
        }
    });

    get("/item", (req, res) -> {
        if (isNullOrEmpty(req.queryParams("qf")) || isNullOrEmpty(req.queryParams("qv"))) {
            halt(400, "Must supply field and value query parameters 'qf' and 'qv'");
        }
        itemReqs.mark();
        Timer.Context context = respTime.time();
        try (Handle hdl = dbi.open()) {
            if (findFieldId(hdl, req.queryParams("qf")) != -1) {
                List<String> results = findItems(hdl, req.queryParams("qf"), req.queryParams("qv"),
                        req.queryParamsValues("rf"));
                if (results.size() > 0) {
                    res.type("application/json");
                    return "{ " + jsonValue("field", req.queryParams("qf"), true) + ",\n"
                            + jsonValue("value", req.queryParams("qv"), true) + ",\n" + jsonValue("items",
                                    results.stream().collect(Collectors.joining(",", "[", "]")), false)
                            + "\n" + " }";
                } else {
                    res.status(404);
                    return "No items found for: " + req.queryParams("qf") + "::" + req.queryParams("qv");
                }
            } else {
                res.status(404);
                return "No such field: " + req.queryParams("qf");
            }
        } catch (Exception e) {
            if (null != reporter)
                reporter.reportError(e);
            res.status(500);
            return "Internal system error: " + e.getMessage();
        } finally {
            context.stop();
        }
    });

    awaitInitialization();
}

From source file:com.mapr.PurchaseLog.java

public static void main(String[] args) throws IOException {
    Options opts = new Options();
    CmdLineParser parser = new CmdLineParser(opts);
    try {/*from   ww w  . j ava 2 s  .c om*/
        parser.parseArgument(args);
    } catch (CmdLineException e) {
        System.err.println("Usage: -count <number>G|M|K [ -users number ]  log-file user-profiles");
        return;
    }

    Joiner withTab = Joiner.on("\t");

    // first generate lots of user definitions
    SchemaSampler users = new SchemaSampler(
            Resources.asCharSource(Resources.getResource("user-schema.txt"), Charsets.UTF_8).read());
    File userFile = File.createTempFile("user", "tsv");
    BufferedWriter out = Files.newBufferedWriter(userFile.toPath(), Charsets.UTF_8);
    for (int i = 0; i < opts.users; i++) {
        out.write(withTab.join(users.sample()));
        out.newLine();
    }
    out.close();

    // now generate a session for each user
    Splitter onTabs = Splitter.on("\t");
    Splitter onComma = Splitter.on(",");

    Random gen = new Random();
    SchemaSampler intermediate = new SchemaSampler(
            Resources.asCharSource(Resources.getResource("hit_step.txt"), Charsets.UTF_8).read());

    final int COUNTRY = users.getFieldNames().indexOf("country");
    final int CAMPAIGN = intermediate.getFieldNames().indexOf("campaign_list");
    final int SEARCH_TERMS = intermediate.getFieldNames().indexOf("search_keywords");
    Preconditions.checkState(COUNTRY >= 0, "Need country field in user schema");
    Preconditions.checkState(CAMPAIGN >= 0, "Need campaign_list field in step schema");
    Preconditions.checkState(SEARCH_TERMS >= 0, "Need search_keywords field in step schema");

    out = Files.newBufferedWriter(new File(opts.out).toPath(), Charsets.UTF_8);

    for (String line : Files.readAllLines(userFile.toPath(), Charsets.UTF_8)) {
        long t = (long) (TimeUnit.MILLISECONDS.convert(30, TimeUnit.DAYS) * gen.nextDouble());
        List<String> user = Lists.newArrayList(onTabs.split(line));

        // pick session length
        int n = (int) Math.floor(-30 * Math.log(gen.nextDouble()));

        for (int i = 0; i < n; i++) {
            // time on page
            int dt = (int) Math.floor(-20000 * Math.log(gen.nextDouble()));
            t += dt;

            // hit specific values
            JsonNode step = intermediate.sample();

            // check for purchase
            double p = 0.01;
            List<String> campaigns = Lists.newArrayList(onComma.split(step.get("campaign_list").asText()));
            List<String> keywords = Lists.newArrayList(onComma.split(step.get("search_keywords").asText()));
            if ((user.get(COUNTRY).equals("us") && campaigns.contains("5"))
                    || (user.get(COUNTRY).equals("jp") && campaigns.contains("7")) || keywords.contains("homer")
                    || keywords.contains("simpson")) {
                p = 0.5;
            }

            String events = gen.nextDouble() < p ? "1" : "-";

            out.write(Long.toString(t));
            out.write("\t");
            out.write(line);
            out.write("\t");
            out.write(withTab.join(step));
            out.write("\t");
            out.write(events);
            out.write("\n");
        }
    }
    out.close();
}