Example usage for java.lang Thread sleep

List of usage examples for java.lang Thread sleep

Introduction

In this page you can find the example usage for java.lang Thread sleep.

Prototype

public static native void sleep(long millis) throws InterruptedException;

Source Link

Document

Causes the currently executing thread to sleep (temporarily cease execution) for the specified number of milliseconds, subject to the precision and accuracy of system timers and schedulers.

Usage

From source file:deck36.storm.plan9.php.KittenRobbersTopology.java

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

    String env = null;// w  w w . ja  va 2  s. co  m

    if (args != null && args.length > 0) {
        env = args[0];
    }

    if (!"dev".equals(env))
        if (!"prod".equals(env)) {
            System.out.println("Usage: $0 (dev|prod)\n");
            System.exit(1);
        }

    // Topology config
    Config conf = new Config();

    // Load parameters and add them to the Config
    Map configMap = YamlLoader.loadYamlFromResource("config_" + env + ".yml");

    conf.putAll(configMap);

    log.info(JSONValue.toJSONString((conf)));

    // Set topology loglevel to DEBUG
    conf.put(Config.TOPOLOGY_DEBUG, JsonPath.read(conf, "$.deck36_storm.debug"));

    // Create Topology builder
    TopologyBuilder builder = new TopologyBuilder();

    // if there are not special reasons, start with parallelism hint of 1
    // and multiple tasks. By that, you can scale dynamically later on.
    int parallelism_hint = JsonPath.read(conf, "$.deck36_storm.default_parallelism_hint");
    int num_tasks = JsonPath.read(conf, "$.deck36_storm.default_num_tasks");

    String badgeName = KittenRobbersTopology.class.getSimpleName();

    // construct command to invoke the external bolt implementation
    ArrayList<String> command = new ArrayList(15);

    // Add main execution program (php, hhvm, zend, ..) and parameters
    command.add((String) JsonPath.read(conf, "$.deck36_storm.php.executor"));
    command.addAll((List<String>) JsonPath.read(conf, "$.deck36_storm.php.executor_params"));

    // Add main command to be executed (app/console, the phar file, etc.) and global context parameters (environment etc.)
    command.add((String) JsonPath.read(conf, "$.deck36_storm.php.main"));
    command.addAll((List<String>) JsonPath.read(conf, "$.deck36_storm.php.main_params"));

    // Add main route to be invoked and its parameters
    command.add((String) JsonPath.read(conf, "$.deck36_storm.KittenRobbersFromOuterSpaceBolt.main"));
    List boltParams = (List<String>) JsonPath.read(conf,
            "$.deck36_storm.KittenRobbersFromOuterSpaceBolt.params");
    if (boltParams != null)
        command.addAll(boltParams);

    // Log the final command
    log.info("Command to start bolt for KittenRobbersFromOuterSpace: " + Arrays.toString(command.toArray()));

    // Add constructed external bolt command to topology using MultilangAdapterBolt
    builder.setBolt("badge", new MultilangAdapterTickTupleBolt(command,
            (Integer) JsonPath.read(conf, "$.deck36_storm.KittenRobbersFromOuterSpaceBolt.robber_frequency"),
            "badge"), parallelism_hint).setNumTasks(num_tasks);

    builder.setBolt("rabbitmq_router",
            new Plan9RabbitMQRouterBolt(
                    (String) JsonPath.read(conf,
                            "$.deck36_storm.KittenRobbersFromOuterSpaceBolt.rabbitmq.target_exchange"),
                    "KittenRobbers" // RabbitMQ routing key
            ), parallelism_hint).setNumTasks(num_tasks).shuffleGrouping("badge");

    builder.setBolt("rabbitmq_producer", new Plan9RabbitMQPushBolt(), parallelism_hint).setNumTasks(num_tasks)
            .shuffleGrouping("rabbitmq_router");

    if ("dev".equals(env)) {
        LocalCluster cluster = new LocalCluster();
        cluster.submitTopology(badgeName + System.currentTimeMillis(), conf, builder.createTopology());
        Thread.sleep(2000000);
    }

    if ("prod".equals(env)) {
        StormSubmitter.submitTopology(badgeName + "-" + System.currentTimeMillis(), conf,
                builder.createTopology());
    }

}

From source file:org.atomspace.pi2c.runtime.Server.java

public static void main(String[] args) throws Exception {
    System.err.println("::: ----------------------------------------------------------------------- :::");
    System.err.println("::: ------------------------------  STARTING  ------------------------------:::");
    System.err.println("::: ----------------------------------------------------------------------- :::");
    System.err.println("\n::: SYSTEM-Properties:                                                    :::");
    Set<?> properties = System.getProperties().keySet();
    for (Object object : properties) {
        System.err.println("::: " + object.toString() + " = " + System.getProperty(object.toString()));
    }//from w w  w . j  a va  2 s  .  co m
    System.err.println("\n::: ENV-Properties:                                                       :::");
    properties = System.getenv().keySet();
    for (Object object : properties) {
        System.err.println("::: " + object.toString() + " = " + System.getenv(object.toString()));
    }

    windows = System.getProperty("os.name").toLowerCase().startsWith("windows");
    linux = System.getProperty("os.name").toLowerCase().startsWith("linux");
    sunos = System.getProperty("os.name").toLowerCase().startsWith("sun");
    freebsd = System.getProperty("os.name").toLowerCase().startsWith("freebsd");

    if (linux || sunos) {
        //USR2-Signal-Handel lookup internal Server STATUS for Linux or SunOS
        System.err.println("::: " + new Date() + "::: run unter Linux or SunOS :::");
        addUnixSignalStatusHandle();
    } else if (freebsd) {
        System.err.println("::: " + new Date() + "::: run unter FreeBSD :::");
    } else if (windows) {
        //Gracefull Shutdown JFrame for Windows, because can not kill -15 <pid> on Window or in Eclipse Console
        System.err.println("::: " + new Date() + " ::: run unter windows :::");
        addWindowsShutdownHandle();
    } else {
        System.err.println("UNKNOWN OS:" + System.getProperty("os.name"));
    }

    status = STATUS_STARTING;

    Server server = new Server();
    Thread serverThread = new Thread(server);
    serverThread.start();

    //Thread can stop by Shutdown-Hook
    while (true) {
        try {
            Thread.sleep(10000);
        } catch (InterruptedException e) {
            e.printStackTrace();
            break;
        }
    }

}

From source file:cn.com.inhand.devicenetworks.ap.mq.rabbitmq.TaskNotificationConsumer.java

public static void main(String[] agrs) throws Exception {
    String path = "file:/home/han/myworks/workroom/NetBeansProjects/WSAP/RabbitMQDemo/RabbitMQDemo/src/main/webapp/WEB-INF/MQXMLApplicationContext.xml";
    AbstractApplicationContext ctx = new FileSystemXmlApplicationContext(path);
    RabbitTemplate template = ctx.getBean(RabbitTemplate.class);
    template.convertAndSend("Hello, world!");
    Thread.sleep(1000);
    ctx.destroy();//from   www. j  a  v a  2 s .  c  o  m
}

From source file:core.sample.pool.PoolTester.java

public static void main(String[] args) {
    log.debug("\n\n********* Starting Test ************************");
    PoolTester pt = new PoolTester();

    //    pt.runWithNotify(); // test using wait() and notify()
    //    pt.runWithoutNotify(); // test using without wait() and notify()
    pt.runMultiple(6); // multiple thread run simulation
    //    pt.runAsyncTask(); // run asynchronously without waiting for results.

    try {/*from   www . ja v  a  2  s . c om*/
        Thread.sleep(8000); // sleep for 8 secs
    } catch (InterruptedException e) {
        log.error("", e);
    }

    log.debug(" \n    <<<< Shutting down pool >>> ");
    pt.shutdown();
    log.debug("\n     <<<< Finished Shutting down pool >>> ");
    log.debug("\n\n********* Finished Test *************************");
}

From source file:fresto.datastore.EventLogWriter.java

public static void main(String[] args) throws Exception {
    if (args.length != 2) {
        LOGGER.severe("Argumests needed : <frontHost> <frontPort>");
        System.exit(1);/*ww w  .j  a v a2 s . c  o  m*/
    } else {
        frontHost = args[0];
        frontPort = args[1];
        LOGGER.info("Connecting... " + frontHost + ":" + frontPort + " with SUB");
    }

    final ZMQ.Context context = ZMQ.context(1);

    final FrestoEventQueue frestoEventQueue = new FrestoEventQueue();

    final Thread queueMonitorThread = new Thread() {
        Logger _LOGGER = Logger.getLogger("logWriteThread");

        @Override
        public void run() {
            while (work) {
                try {
                    _LOGGER.info("frestoEventQueue size = " + frestoEventQueue.size());
                    Thread.sleep(1000);
                } catch (InterruptedException ie) {
                }

            }
        }
    };

    final Thread logWriteThread = new Thread() {
        Logger _LOGGER = Logger.getLogger("logWriteThread");

        @Override
        public void run() {
            //FrestoStopWatch _watch = new FrestoStopWatch();
            //FrestoStopWatch _durationWatch = new FrestoStopWatch();

            EventLogWriter eventLogWriter = new EventLogWriter();

            // Open database
            //eventLogWriter.openTitanGraph();

            ZMQ.Socket receiver = null;
            //if("pull".equalsIgnoreCase(subOrPull)) {
            //   receiver = context.socket(ZMQ.PULL);
            //   receiver.connect("tcp://" + frontHost + ":" + frontPort);
            //} else if("sub".equalsIgnoreCase(subOrPull)) {
            receiver = context.socket(ZMQ.SUB);
            receiver.connect("tcp://" + frontHost + ":" + frontPort);
            receiver.subscribe("".getBytes());
            //} else {
            //   LOGGER.severe(subOrPull + " is not supported.");
            //   System.exit(1);
            //}

            //Consume socket data
            frestoEventQueue.setPullerSocket(receiver);
            frestoEventQueue.start();

            int waitingEventCount = 0;
            //int count = 0;
            //long elapsedTime = 0;
            //long duration = 0;

            //_durationWatch.start();

            while (work) {

                // To wait until at least one event in queue
                if (frestoEventQueue.isEmpty()) {
                    try {
                        //_LOGGER.info("FrestoEventQueue is empty. Waiting " + SLEEP_TIME + "ms...");
                        Thread.sleep(SLEEP_TIME);
                        continue;
                    } catch (InterruptedException ie) {
                    }
                }

                waitingEventCount = frestoEventQueue.size();

                for (int i = 0; i < waitingEventCount; i++) {
                    //_watch.start();
                    //count++;

                    FrestoEvent frestoEvent = frestoEventQueue.poll();

                    try {
                        eventLogWriter.writeEventData(frestoEvent.topic, frestoEvent.eventBytes);
                    } catch (Exception e) {
                        e.printStackTrace();
                    } finally {
                        //
                    }

                    //elapsedTime += _watch.stop();
                    //duration += _durationWatch.stop();

                    //if(count == maxCommitCount) {
                    //   eventLogWriter.commitGraph();
                    //   _LOGGER.info(count + " events processed for " + elapsedTime + " ms. (total time " + duration + " ms.) Remaining events " + frestoEventQueue.size());
                    //   
                    //   count = 0;
                    //   elapsedTime = 0;
                    //   duration = 0;
                    //   // Stop FOR clause
                    //}
                }

                //eventLogWriter.commitGraph();

                _LOGGER.info("Remaining events " + frestoEventQueue.size());

                //count = 0;
                //elapsedTime = 0;
                //duration = 0;
            }
            _LOGGER.info("Shutting down...");

            //if(g.isOpen()) {
            //   g.commit();
            //   g.shutdown();
            //}

            receiver.close();
            context.term();

            _LOGGER.info("Good bye.");
        }
    };

    Runtime.getRuntime().addShutdownHook(new Thread() {
        @Override
        public void run() {
            System.out.println(" Interrupt received, killing logger");
            // To break while clause
            frestoEventQueue.stopWork();
            work = false;

            try {
                logWriteThread.join();
                frestoEventQueue.join();
                //queueMonitorThread.join();

            } catch (InterruptedException e) {
                //
            }
        }
    });

    //queueMonitorThread.start();
    logWriteThread.start();

}

From source file:com.arpnetworking.tsdaggregator.TsdAggregator.java

/**
 * Entry point for Time Series Data (TSD) Aggregator.
 *
 * @param args the command line arguments
 *///from  www .j  av a  2s  . c o  m
public static void main(final String[] args) {
    LOGGER.info("Launching tsd-aggregator");

    // Global initialization
    Thread.setDefaultUncaughtExceptionHandler(new Thread.UncaughtExceptionHandler() {
        @Override
        public void uncaughtException(final Thread thread, final Throwable throwable) {
            LOGGER.error("Unhandled exception!", throwable);
        }
    });

    Runtime.getRuntime().addShutdownHook(new Thread(new Runnable() {
        @Override
        public void run() {
            final LoggerContext context = (LoggerContext) LoggerFactory.getILoggerFactory();
            context.stop();
        }
    }));

    System.setProperty("org.vertx.logger-delegate-factory-class-name",
            "org.vertx.java.core.logging.impl.SLF4JLogDelegateFactory");

    // Run the tsd aggregator
    if (args.length != 1) {
        throw new RuntimeException("No configuration file specified");
    }
    LOGGER.debug(String.format("Loading configuration from file; file=%s", args[0]));

    final File configurationFile = new File(args[0]);
    final Configurator<TsdAggregator, TsdAggregatorConfiguration> configurator = new Configurator<>(
            TsdAggregator.class, TsdAggregatorConfiguration.class);
    final ObjectMapper objectMapper = TsdAggregatorConfiguration.createObjectMapper();
    final DynamicConfiguration configuration = new DynamicConfiguration.Builder().setObjectMapper(objectMapper)
            .addSourceBuilder(
                    new JsonNodeFileSource.Builder().setObjectMapper(objectMapper).setFile(configurationFile))
            .addTrigger(new FileTrigger.Builder().setFile(configurationFile).build()).addListener(configurator)
            .build();

    configuration.launch();

    final AtomicBoolean isRunning = new AtomicBoolean(true);
    Runtime.getRuntime().addShutdownHook(new Thread(new Runnable() {
        @Override
        public void run() {
            LOGGER.info("Stopping tsd-aggregator");
            configuration.shutdown();
            configurator.shutdown();
            isRunning.set(false);
        }
    }));

    while (isRunning.get()) {
        try {
            Thread.sleep(30000);
        } catch (final InterruptedException e) {
            break;
        }
    }

    LOGGER.info("Exiting tsd-aggregator");
}

From source file:cz.alej.michalik.totp.util.TOTP.java

/**
 * Ukzka TOTP pro zprvu "12345678901234567890"
 *//* ww w .  j a  va  2 s .co  m*/
public static void main(String[] args) {
    // GEZDGNBVGY3TQOJQGEZDGNBVGY3TQOJQ v base32
    String secret = "12345678901234567890";
    System.out.printf("Heslo je: %s \nV Base32 to je: %s\n", secret,
            new Base32().encodeToString(secret.getBytes()));
    TOTP t = new TOTP(secret.getBytes());
    System.out.printf("%s\n", t);
    while (true) {
        int time = Integer.valueOf(new SimpleDateFormat("ss").format(new Date()));
        if (time % 30 == 0) {
            System.out.printf("%s\n", t);
        }
        try {
            Thread.sleep(1000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}

From source file:edu.indiana.d2i.sloan.internal.SwitchVMSimulator.java

/**
 * @param args//from   w  ww  . j  ava 2  s . c  om
 */
public static void main(String[] args) {
    SwitchVMSimulator simulator = new SwitchVMSimulator();

    CommandLineParser parser = new PosixParser();

    try {
        CommandLine line = simulator.parseCommandLine(parser, args);

        String wdir = line.getOptionValue(CMD_FLAG_VALUE.get(CMD_FLAG_KEY.WORKING_DIR));
        String mode = line.getOptionValue(CMD_FLAG_VALUE.get(CMD_FLAG_KEY.VM_MODE));
        String policyFilePath = line.getOptionValue(CMD_FLAG_VALUE.get(CMD_FLAG_KEY.POLICY_PATH));

        if (!HypervisorCmdSimulator.resourceExist(wdir)) {
            logger.error(String.format("Cannot find VM working dir: %s", wdir));
            System.exit(ERROR_CODE.get(ERROR_STATE.VM_NOT_EXIST));
        }

        VMMode requestedMode = HypervisorCmdSimulator.getVMMode(mode);

        if (requestedMode == null) {
            logger.error(String.format("Invalid requested mode: %s, can only be %s or %s", mode,
                    VMMode.MAINTENANCE.toString(), VMMode.SECURE.toString()));
            System.exit(ERROR_CODE.get(ERROR_STATE.INVALID_VM_MODE));
        }

        if (!HypervisorCmdSimulator.resourceExist(policyFilePath)) {
            logger.error(String.format("Cannot find plicy file: %s", policyFilePath));
            System.exit(ERROR_CODE.get(ERROR_STATE.FIREWALL_POLICY_NOT_EXIST));
        }

        // load VM state file
        Properties prop = new Properties();
        String filename = HypervisorCmdSimulator.cleanPath(wdir) + HypervisorCmdSimulator.VM_INFO_FILE_NAME;

        prop.load(new FileInputStream(new File(filename)));

        // cannot switch when VM is not running
        VMState currentState = VMState.valueOf(prop.getProperty(CMD_FLAG_VALUE.get(CMD_FLAG_KEY.VM_STATE)));

        if (!currentState.equals(VMState.RUNNING)) {
            logger.error("Cannot perform switch when VM is not running");
            System.exit(ERROR_CODE.get(ERROR_STATE.VM_NOT_RUNNING));
        }

        // get current mode
        VMMode currentMode = VMMode.valueOf(prop.getProperty(CMD_FLAG_VALUE.get(CMD_FLAG_KEY.VM_MODE)));

        if (currentMode.equals(requestedMode)) {
            logger.error(String.format("VM is already in the requested mode: %s", requestedMode.toString()));
            System.exit(ERROR_CODE.get(ERROR_STATE.VM_ALREADY_IN_REQUESTED_MODE));
        }

        // switch VM
        try {
            Thread.sleep(1000);
        } catch (InterruptedException e) {
            logger.error(e.getMessage());
        }

        // update firewall policy
        prop.put(CMD_FLAG_VALUE.get(CMD_FLAG_KEY.POLICY_PATH), policyFilePath);

        // update VM status file, i.e. set mode to the requested mode
        prop.put(CMD_FLAG_VALUE.get(CMD_FLAG_KEY.VM_MODE), requestedMode.toString());

        // save VM state file back
        prop.store(new FileOutputStream(new File(filename)), "");

        // success
        System.exit(0);
    } catch (ParseException e) {
        logger.error(String.format("Cannot parse input arguments: %s%n, expected:%n%s",
                StringUtils.join(args, " "), simulator.getUsage(100, "", 5, 5, "")));

        System.exit(ERROR_CODE.get(ERROR_STATE.INVALID_INPUT_ARGS));
    } catch (FileNotFoundException e) {
        logger.error(String.format("Cannot find vm state file: %s", e.getMessage()));

        System.exit(ERROR_CODE.get(ERROR_STATE.VM_STATE_FILE_NOT_FOUND));
    } catch (IOException e) {
        logger.error(e.getMessage(), e);
        System.exit(ERROR_CODE.get(ERROR_STATE.IO_ERR));
    }
}

From source file:de.uniwue.info6.database.SQLParserTest.java

public static void main(String[] args) throws Exception {
    String test = "Dies ist ein einfacher Test";
    System.out.println(StringTools.forgetOneWord(test));

    System.exit(0);//w  w  w .j  av a 2 s.  c  o  m
    // SimpleTupel<String, Integer> test1 =  new SimpleTupel<String, Integer>("test1", 1);
    // SimpleTupel<String, Integer> test2 =  new SimpleTupel<String, Integer>("test1", 12);

    // ArrayList<SimpleTupel<String, Integer>> test = new ArrayList<SimpleTupel<String, Integer>>();
    // test.add(test1);
    // System.out.println(test1.equals(test2));
    // System.exit(0);

    final boolean resetDb = true;
    // Falls nur nach einer bestimmten Aufgabe gesucht wird
    final Integer exerciseID = 39;
    final Integer scenarioID = null;
    final int threadSize = 1;

    final EquivalenceLock<Long[]> equivalenceLock = new EquivalenceLock<Long[]>();
    final Long[] performance = new Long[] { 0L, 0L };

    // ------------------------------------------------ //
    final ScenarioDao scenarioDao = new ScenarioDao();
    final ExerciseDao exerciseDao = new ExerciseDao();
    final ExerciseGroupDao groupDao = new ExerciseGroupDao();
    final UserDao userDao = new UserDao();
    final ArrayList<Thread> threads = new ArrayList<Thread>();

    // ------------------------------------------------ //
    try {
        ConnectionManager.offline_instance();
        if (resetDb) {
            Cfg.inst().setProp(MAIN_CONFIG, IMPORT_EXAMPLE_SCENARIO, true);
            Cfg.inst().setProp(MAIN_CONFIG, FORCE_RESET_DATABASE, true);
            new GenerateData().resetDB();
            ConnectionTools.inst().addSomeTestData();
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
    // ------------------------------------------------ //

    final List<Scenario> scenarios = scenarioDao.findAll();

    try {
        // ------------------------------------------------ //
        String userID;
        for (int i = 2; i < 100; i++) {
            userID = "user_" + i;
            User userToInsert = new User();
            userToInsert.setId(userID);
            userToInsert.setIsAdmin(false);
            userDao.insertNewInstance(userToInsert);
        }
        // ------------------------------------------------ //

        for (int i = 0; i < threadSize; i++) {
            Thread thread = new Thread() {

                public void run() {
                    // ------------------------------------------------ //
                    try {
                        Thread.sleep(new Random().nextInt(30));
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    // ------------------------------------------------ //

                    User user = userDao.getRandom();
                    Thread.currentThread().setName(user.getId());
                    System.err.println(
                            "\n\nINFO (ueps): Thread '" + Thread.currentThread().getName() + "' started\n");

                    // ------------------------------------------------ //

                    for (Scenario scenario : scenarios) {
                        if (scenarioID != null && !scenario.getId().equals(scenarioID)) {
                            continue;
                        }

                        System.out.println(StringUtils.repeat("#", 90));
                        System.out.println("SCENARIO: " + scenario.getId());

                        // ------------------------------------------------ //
                        for (ExerciseGroup group : groupDao.findByScenario(scenario)) {
                            System.out.println(StringUtils.repeat("#", 90));
                            System.out.println("GROUP: " + group.getId());
                            System.out.println(StringUtils.repeat("#", 90));
                            List<Exercise> exercises = exerciseDao.findByExGroup(group);

                            // ------------------------------------------------ //
                            for (Exercise exercise : exercises) {
                                if (exerciseID != null && !exercise.getId().equals(exerciseID)) {
                                    continue;
                                }
                                long startTime = System.currentTimeMillis();

                                for (int i = 0; i < 100; i++) {
                                    String userID = "user_" + new Random().nextInt(100000);
                                    User userToInsert = new User();
                                    userToInsert.setId(userID);
                                    userToInsert.setIsAdmin(false);
                                    userDao.insertNewInstance(userToInsert);
                                    user = userDao.getById(userID);

                                    List<SolutionQuery> solutions = new ExerciseDao().getSolutions(exercise);
                                    String solution = solutions.get(0).getQuery();
                                    ExerciseController exc = new ExerciseController().init_debug(scenario,
                                            exercise, user);
                                    exc.setUserString(solution);

                                    String fd = exc.getFeedbackList().get(0).getFeedback();
                                    System.out.println("Used Query: " + solution);
                                    if (fd.trim().toLowerCase().equals("bestanden")) {
                                        System.out.println(exercise.getId() + ": " + fd);
                                    } else {
                                        System.err.println(exercise.getId() + ": " + fd + "\n");
                                    }
                                    System.out.println(StringUtils.repeat("-", 90));
                                }

                                long elapsedTime = System.currentTimeMillis() - startTime;

                                // if (i > 5) {
                                //   try {
                                //     equivalenceLock.lock(performance);
                                //     performance[0] += elapsedTime;
                                //     performance[1]++;
                                //   } catch (Exception e) {
                                //   } finally {
                                //     equivalenceLock.release(performance);
                                //   }
                                // }
                            }
                        }
                    }

                    System.err
                            .println("INFO (ueps): Thread '" + Thread.currentThread().getName() + "' stopped");
                }
            };
            thread.start();
            threads.add(thread);
        }

        for (Thread thread : threads) {
            thread.join();
        }

        // try {
        //   equivalenceLock.lock(performance);

        //   long elapsedTime = (performance[0] / performance[1]);
        //   System.out.println("\n" + String.format("perf : %d.%03dsec", elapsedTime / 1000, elapsedTime % 1000));
        // } catch (Exception e) {
        // } finally {
        //   equivalenceLock.release(performance);
        // }

    } finally {
    }
}

From source file:com.amazonaws.services.iot.client.sample.shadowEcho.ShadowEchoSample.java

public static void main(String args[])
        throws IOException, AWSIotException, AWSIotTimeoutException, InterruptedException {
    CommandArguments arguments = CommandArguments.parse(args);
    initClient(arguments);/*from  w  w  w  . j a v  a 2 s . c  o m*/

    String thingName = arguments.getNotNull("thingName", SampleUtil.getConfig("thingName"));
    AWSIotDevice device = new AWSIotDevice(thingName);

    awsIotClient.attach(device);
    awsIotClient.connect();

    // Delete existing document if any
    device.delete();

    ObjectMapper objectMapper = new ObjectMapper();
    objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);

    Thing thing = new Thing();

    while (true) {
        long desired = thing.state.desired.counter;
        thing.state.reported.counter = desired;
        thing.state.desired.counter = desired + 1;

        String jsonState = objectMapper.writeValueAsString(thing);

        try {
            // Send updated document to the shadow
            device.update(jsonState);
            System.out.println(System.currentTimeMillis() + ": >>> " + jsonState);
        } catch (AWSIotException e) {
            System.out.println(System.currentTimeMillis() + ": update failed for " + jsonState);
            continue;
        }

        try {
            // Retrieve updated document from the shadow
            String shadowState = device.get();
            System.out.println(System.currentTimeMillis() + ": <<< " + shadowState);

            thing = objectMapper.readValue(shadowState, Thing.class);
        } catch (AWSIotException e) {
            System.out.println(System.currentTimeMillis() + ": get failed for " + jsonState);
            continue;
        }

        Thread.sleep(1000);
    }

}