Runs the benchmark.

@throws Exception if an exception occurs
772096
public void run() throws Exception {
        ExecutorService exec = Executors.newCachedThreadPool();
        final Phaser phaser = new Phaser();

        installShutdownHook();

        phaser.register();
        
        String[] servers = urls.split(",");
        io.nats.client.Options.Builder builder = new io.nats.client.Options.Builder();
        builder.noReconnect();
        builder.connectionName("StanBench");
        builder.servers(servers);

        if (secure) {
            builder.secure();
        }

        builder.errorListener(new ErrorListener(){
            @Override
            public void slowConsumerDetected(Connection conn, Consumer consumer) {
                System.err.println("Slow consumer detected on client side.");
            }
        
            @Override
            public void exceptionOccurred(Connection conn, Exception ex) {
                System.err.printf("Connection exception %s, connection status is %s\n", ex, conn.getStatus());
                System.err.printf("Sent=%d, Received=%d\n", published.get(), received.get());
            }
        
            @Override
            public void errorOccurred(Connection conn, String err) {
                System.err.println("Error message from server "+err);
            }
        });

        natsOptions = builder.build();

        bench = new Benchmark("NATS Streaming");

        // Run Subscribers first
        for (int i = 0; i < numSubs; i++) {
            phaser.register();
            String subId = String.format("%s-sub-%d", clientId, i);
            exec.execute(new SubWorker(phaser, numMsgs, size, ignoreOld, subId));
        }

        // Wait for subscribers threads to initialize
        phaser.arriveAndAwaitAdvance();

        // Now publishers
        List<Integer> pubCounts = io.nats.streaming.examples.benchmark.Utils.msgsPerClient(numMsgs, numPubs);
        for (int i = 0; i < numPubs; i++) {
            phaser.register();
            String pubId = String.format("%s-pub-%d", clientId, i);
            exec.execute(new PubWorker(phaser, pubCounts.get(i), size, async, pubId));
        }

        System.out.printf("Starting benchmark [msgs=%d, msgsize=%d, pubs=%d, subs=%d]\n", numMsgs,
                size, numPubs, numSubs);

        // Wait for subscribers and publishers to finish
        phaser.arriveAndAwaitAdvance();

        // We're done. Clean up and report.
        Runtime.getRuntime().removeShutdownHook(shutdownHook);

        bench.close();
        System.out.println(bench.report());

        if (csvFileName != null) {
            String csv = bench.csv();
            Path csvFile = Paths.get(csvFileName);
            Files.write(csvFile, Collections.singletonList(csv), Charset.forName("UTF-8"));
        }

        exec.shutdown();
    }
1126764
@Override
	protected void run() throws Exception {

		final String iterationId = getConfiguration().getIterationId();
		if (iterationId == null || iterationId.length() == 0) {
			throw new Exception("Missing iteration ID in the task configuration");
		}

		final String brokerID = createBrokerIdString(getEnvironment().getJobID(), iterationId ,
				getEnvironment().getTaskInfo().getIndexOfThisSubtask());

		final long iterationWaitTime = getConfiguration().getIterationWaitTime();
		final boolean shouldWait = iterationWaitTime > 0;

		final BlockingQueue<StreamRecord<OUT>> dataChannel = new ArrayBlockingQueue<StreamRecord<OUT>>(1);

		// offer the queue for the tail
		BlockingQueueBroker.INSTANCE.handIn(brokerID, dataChannel);
		LOG.info("Iteration head {} added feedback queue under {}", getName(), brokerID);

		// do the work
		try {
			@SuppressWarnings("unchecked")
			RecordWriterOutput<OUT>[] outputs = (RecordWriterOutput<OUT>[]) getStreamOutputs();

			// If timestamps are enabled we make sure to remove cyclic watermark dependencies
			if (isSerializingTimestamps()) {
				synchronized (getCheckpointLock()) {
					for (RecordWriterOutput<OUT> output : outputs) {
						output.emitWatermark(new Watermark(Long.MAX_VALUE));
					}
				}
			}

			while (running) {
				StreamRecord<OUT> nextRecord = shouldWait ?
					dataChannel.poll(iterationWaitTime, TimeUnit.MILLISECONDS) :
					dataChannel.take();

				if (nextRecord != null) {
					synchronized (getCheckpointLock()) {
						for (RecordWriterOutput<OUT> output : outputs) {
							output.collect(nextRecord);
						}
					}
				}
				else {
					// done
					break;
				}
			}
		}
		finally {
			// make sure that we remove the queue from the broker, to prevent a resource leak
			BlockingQueueBroker.INSTANCE.remove(brokerID);
			LOG.info("Iteration head {} removed feedback queue under {}", getName(), brokerID);
		}
	}
945021
public void run() {
		try {
			for (String mbean : mbeanMap.keySet()) {
				MBeanHolder h = mbeanMap.get(mbean);
				h.publish();
			}
		} catch (Exception ex) {
			// Robust exception to prevent thread death
			log.warning("Exception thrown sampling Mbeans");
			log.throwing(this.getClass().getName(),
					"Exception thrown sampling Mbeans:", ex);
		}
	}
170940
public void run() {
		try {
			Object result = execute();
			if (!aborted) {
				this.retval = result;
				finished = true;
			}
		}
		catch (InterruptedException ie) {
			//
		}
		catch (Throwable t) {
			execException = t;
			finished = true;
		}
	}
1178459
@Override
    public void run ()
    {
        try {
            _running = true;
            willStart();

            while (isRunning()) {
                try {
                    iterate();
                } catch (Exception e) {
                    handleIterateFailure(e);
                }
            }

        } catch (Throwable t) {
            log.warning("Looping thread terminated with exception.", "thread", this, t);

        } finally {
            // running needs to be false even if this exited due to a Throwable from iterate
            _running = false;
            didShutdown();
        }
    }
1243261
@Override
	public void run() {
		final long stamp = lock.writeLock();
		try {
			Iterator<ErrorCounter> i = errorCounters.values().iterator();
			while (i.hasNext()) {
				if (i.next().isEmpty()) {
					i.remove();
				}
			}
		} finally {
			lock.unlockWrite(stamp);
		}		
	}
970440
public void run()
	{
		while (true) {
			final long start = System.currentTimeMillis();
			long remaining;
			Cache c;
			synchronized (lock) {
				c = cache;
				remaining = sweepInterval * 1000;
				while (remaining > 0 && cache != null) {
					try {
						lock.wait(remaining);
					}
					catch (final InterruptedException e) {}
					remaining = start + sweepInterval * 1000 - System.currentTimeMillis();
				}
				if (cache == null)
					break;
			}
			c.removeExpired();
		}
	}
1112004
public static void main(String[] args) throws InterruptedException {
		final ExecutorService executorService = Executors.newFixedThreadPool(1000);
		BenchmarkUtils.run(1, 2,
			// low contention - single thread
			new BenchmarkUtils.Task("1") {
				@Override
				public void perform() throws Exception {
					new MultithreadedTester(TOTAL_TASK_RUNS, 1, executorService).execute();
				}
			},
			// medium contention
			new BenchmarkUtils.Task("CPU") {
				@Override
				public void perform() throws Exception {
					new MultithreadedTester(TOTAL_TASK_RUNS, AVAILABLE_PROCESSORS, executorService).execute();
				}
			},
			// High contention
			new BenchmarkUtils.Task("400") {
				@Override
				public void perform() throws Exception {
					new MultithreadedTester(TOTAL_TASK_RUNS, 400, executorService).execute();
				}
			}
		);
		executorService.shutdown();

		// we're not using Benchmark results here this time, so we have to extract them on our own
		StopwatchSample sampleLo = SimonManager.getStopwatch("MT-1").sample();
		StopwatchSample sampleCpu = SimonManager.getStopwatch("MT-" + AVAILABLE_PROCESSORS).sample();
		StopwatchSample sampleHi = SimonManager.getStopwatch("MT-400").sample();

		System.out.println("\nsampleLo = " + sampleLo);
		System.out.println("sampleCpu = " + sampleCpu);
		System.out.println("sampleHi = " + sampleHi);

		System.out.println("\nGoogle Chart avg:\n" +
			GoogleChartImageGenerator.barChart("MultithreadedContention", SimonUnit.NANOSECOND,
				sampleLo,
				sampleCpu,
				sampleHi));
		System.out.println("\nGoogle Chart avg/min/max:\n" +
			GoogleChartImageGenerator.barChart("MultithreadedContention", SimonUnit.NANOSECOND, true,
				sampleLo,
				sampleCpu,
				sampleHi));
	}
845576
public void run()
    {
        try
        {
            if (!thread.compareAndSet(null, Thread.currentThread()))
            {
                return;
            }

            final IdleStrategy idleStrategy = this.idleStrategy;
            final Agent agent = this.agent;
            try
            {
                agent.onStart();
            }
            catch (final Throwable throwable)
            {
                errorHandler.onError(throwable);
                isRunning = false;
            }

            while (isRunning)
            {
                if (doDutyCycle(idleStrategy, agent))
                {
                    break;
                }
            }

            try
            {
                agent.onClose();
            }
            catch (final Throwable throwable)
            {
                errorHandler.onError(throwable);
            }
        }
        finally
        {
            isClosed = true;
        }
    }
733826
@Benchmark
  @BenchmarkMode(Mode.SampleTime)
  @OutputTimeUnit(TimeUnit.NANOSECONDS)
  public void manyRunnables() throws Exception {
    incrRunnable.val = 0;
    for (int i = 0; i < 500; i++) {
      executor.execute(incrRunnable);
    }
    executor.execute(phaserRunnable);
    phaser.arriveAndAwaitAdvance();
    if (incrRunnable.val != 500) {
      throw new AssertionError();
    }
  }
1185787
@Override
  public void run() {
    long lastUpdate = -1L;
    // Start balancing the clusters
    while (running) {
      try {
        Thread.sleep(updateInterval / 10);
        long now = JobTracker.getClock().getTime();
        if (now - lastUpdate > updateInterval) {
          lastUpdate = now;
          doMoveSlots(clusters);
        }
      } catch (Exception e) {
        LOG.error("Exception while balancing cluster.", e);
      }
    }
  }
390213
public void benchmarkItem() throws Exception {

        // To make an asynchronous procedure call, you need a callback object
        // BenchmarkCallback is a generic callback that keeps track of the transaction results
        // for any given procedure name, which should match the procedure called below.
        ProcedureCallback callback = new BenchmarkCallback("insert_session");

        // generate some random parameter values
        int appid = rand.nextInt(50);
        int deviceid = rand.nextInt(1000000);

        // call the procedure asynchronously, passing in the callback and the procedure name,
        // followed by the input parameters
        client.callProcedure(callback,
                             "insert_session",
                             appid,
                             deviceid
                             );

    }
612998
public void startBenchmark() {
    startTime = System.currentTimeMillis();
    LOG.info("Start to benchmark chronos server");

    Thread t = new Thread() { // new thread to output the metrics
      @Override
      public void run() {
        final long collectPeriod = 10000;
        LOG.info("Start another thread to export benchmark metrics every " + collectPeriod / 1000.0
            + " second");

        int totalCount;
        int totalLatency;
        long exportTime;
        int lastTotalCount = 0;
        int lastTotalLatency = 0;
        long lastExportTime = startTime;

        while (true) {
          try {
            Thread.sleep(collectPeriod);
          } catch (InterruptedException e) {
            LOG.error("Interrupt when sleep to get benchmark metrics, exit immediately");
            System.exit(0);
          }

          exportTime = System.currentTimeMillis();
          totalCount = totalCountInteger.get();
          totalLatency = totalLatencyInteger.get();

          double totalCostTime = (exportTime - startTime) / 1000.0;
          double costTime = (exportTime - lastExportTime) / 1000.0;
          double qps = (totalCount - lastTotalCount) / costTime;
          double latency = (totalLatency - lastTotalLatency) * 1.0 / (totalCount - lastTotalCount);
          System.out.println("Total " + totalCostTime + ", in " + costTime + " seconds, qps: "
              + qps + ", latency: " + latency + "ms");

          lastTotalCount = totalCount;
          lastTotalLatency = totalLatency;
          lastExportTime = exportTime;
        }
      }
    };

    t.setDaemon(true);
    t.start();

    while (true) {
      try {
        long start = System.currentTimeMillis();
        currentTimestamp = chronosClient.getTimestamp();
        totalCountInteger.incrementAndGet();
        totalLatencyInteger.addAndGet((int) (System.currentTimeMillis() - start));

        if (currentTimestamp <= previousTimestamp) { // check correctness
          LOG.error("Fatal error to get a lower timestamp " + currentTimestamp + "(previous is "
              + previousTimestamp + "), exit immediately");
          System.exit(0);
        }
        previousTimestamp = currentTimestamp;

        if (isFailover == true) { // calculate failover time
          double failoverTime = (System.currentTimeMillis() - failoverStartTime) / 1000.0;
          System.out.println("After " + failoverStartTimeString + ", the total failover time is "
              + failoverTime + " seconds");
        }
        isFailover = false;
      } catch (IOException e) {
        LOG.error("Exception to get timestamp");

        if (isFailover == false) {
          failoverStartTime = System.currentTimeMillis();
          failoverStartTimeString = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date(
              failoverStartTime));
          LOG.info("Failover occurs at " + failoverStartTimeString);
        }
        isFailover = true;
      }
    }

  }
936546
public void run() {
        // Reset the stats managed by the client.
        periodicStatsContext.fetchAndResetBaseline();

        // Run in a loop for config.duration seconds.
        final long benchmarkEndTime = app.startTS + (1000l * app.config.duration);
        while (benchmarkEndTime > System.currentTimeMillis()) {

            // GENERATE A RANDOM ROW

            // unique identifier and partition key
            String uuid = UUID.randomUUID().toString();

            // millisecond timestamp
            Date now = new Date();

            // for some odd reason, this will give LONG_MAX if the
            // computed value is > LONG_MAX.
            long val = (long) (rand.nextGaussian() * 1000.0);

            try {
                basicInsert(uuid, val, now);
            }
            catch (IOException e) {
                // Not being super picky about failure handling. If this
                // fails, it will show up in the client-side statistics we
                // print out in printReport().
            }
        }

        // When ready to end processing...
        try {
            // Block until all async calls have returned.
            client.drain();
            // Clean close of the client connection.
            client.close();
        }
        catch (IOException | InterruptedException e) {
            // Live dangerously and ignore this error that probably
            // won't happen at shutdown time.
        }

    }
1051919
@Override
	public final void run () {
		Status result = execute();
		if (result == null) throw new IllegalStateException("Invalid status 'null' returned by the execute method");
		switch (result) {
		case SUCCEEDED:
			success();
			return;
		case FAILED:
			fail();
			return;
		case RUNNING:
			running();
			return;
		default:
			throw new IllegalStateException("Invalid status '" + result.name() + "' returned by the execute method");
		}
	}
1360407
public void run() throws Exception {
		if (this.header.contains("Upgrade: websocket")
				&& this.header.contains("Sec-WebSocket-Version: 13")) {
			runWebSocket();
		}
		if (this.header.contains("GET /livereload.js")) {
			this.outputStream.writeHttp(getClass().getResourceAsStream("livereload.js"),
					"text/javascript");
		}
	}
675934
@Override
	final public void run() {
		try {
			if(args.length>0) handleCommand(args);
			else runImpl();
			status="Done";
		} catch(IOException exception) {
			this.err.println(getName()+": "+exception.getMessage());
			status="IO Error: "+exception.getMessage();
			this.err.flush();
		} catch(SQLException exception) {
			this.err.println(getName()+": "+exception.getMessage());
			status="SQL Error: "+exception.getMessage();
			this.err.flush();
		} catch(ThreadDeath TD) {
			throw TD;
		} catch(Throwable T) {
			ErrorPrinter.printStackTraces(T, this.err);
			status="Error: "+T.toString();
			this.err.flush();
		} finally {
			if(Thread.currentThread()==thread) thread=null;
		}
	}