List of usage examples for java.util.concurrent TimeUnit SECONDS
TimeUnit SECONDS
To view the source code for java.util.concurrent TimeUnit SECONDS.
Click Source Link
From source file:examples.StatePersistence.java
public static void main(String[] args) throws Exception { // Connect to localhost and use the travel-sample bucket final Client client = Client.configure().hostnames("localhost").bucket(BUCKET).build(); // Don't do anything with control events in this example client.controlEventHandler(new ControlEventHandler() { @Override//w w w .ja va 2s.co m public void onEvent(ChannelFlowController flowController, ByteBuf event) { if (DcpSnapshotMarkerRequest.is(event)) { flowController.ack(event); } event.release(); } }); // Print out Mutations and Deletions client.dataEventHandler(new DataEventHandler() { @Override public void onEvent(ChannelFlowController flowController, ByteBuf event) { if (DcpMutationMessage.is(event)) { System.out.println("Mutation: " + DcpMutationMessage.toString(event)); // You can print the content via DcpMutationMessage.content(event).toString(CharsetUtil.UTF_8); } else if (DcpDeletionMessage.is(event)) { System.out.println("Deletion: " + DcpDeletionMessage.toString(event)); } event.release(); } }); // Connect the sockets client.connect().await(); // Try to load the persisted state from file if it exists File file = new File(FILENAME); byte[] persisted = null; if (file.exists()) { FileInputStream fis = new FileInputStream(FILENAME); persisted = IOUtils.toByteArray(fis); fis.close(); } // if the persisted file exists recover, if not start from beginning client.recoverOrInitializeState(StateFormat.JSON, persisted, StreamFrom.BEGINNING, StreamTo.INFINITY) .await(); // Start streaming on all partitions client.startStreaming().await(); // Persist the State ever 10 seconds while (true) { Thread.sleep(TimeUnit.SECONDS.toMillis(10)); // export the state as a JSON byte array byte[] state = client.sessionState().export(StateFormat.JSON); // Write it to a file FileOutputStream output = new FileOutputStream(new File(FILENAME)); IOUtils.write(state, output); output.close(); System.out.println(System.currentTimeMillis() + " - Persisted State!"); } }
From source file:com.lxf.spider.client.ClientWithRequestFuture.java
public static void main(String[] args) throws Exception { // the simplest way to create a HttpAsyncClientWithFuture HttpClient httpclient = HttpClientBuilder.create().setMaxConnPerRoute(5).setMaxConnTotal(5).build(); ExecutorService execService = Executors.newFixedThreadPool(5); FutureRequestExecutionService requestExecService = new FutureRequestExecutionService(httpclient, execService);/*from w w w. j a v a 2 s .c o m*/ try { // Because things are asynchronous, you must provide a ResponseHandler ResponseHandler<Boolean> handler = new ResponseHandler<Boolean>() { public Boolean handleResponse(HttpResponse response) throws ClientProtocolException, IOException { // simply return true if the status was OK return response.getStatusLine().getStatusCode() == 200; } }; // Simple request ... HttpGet request1 = new HttpGet("http://google.com"); HttpRequestFutureTask<Boolean> futureTask1 = requestExecService.execute(request1, HttpClientContext.create(), handler); Boolean wasItOk1 = futureTask1.get(); System.out.println("It was ok? " + wasItOk1); // Cancel a request try { HttpGet request2 = new HttpGet("http://google.com"); HttpRequestFutureTask<Boolean> futureTask2 = requestExecService.execute(request2, HttpClientContext.create(), handler); futureTask2.cancel(true); Boolean wasItOk2 = futureTask2.get(); System.out.println("It was cancelled so it should never print this: " + wasItOk2); } catch (CancellationException e) { System.out.println("We cancelled it, so this is expected"); } // Request with a timeout HttpGet request3 = new HttpGet("http://google.com"); HttpRequestFutureTask<Boolean> futureTask3 = requestExecService.execute(request3, HttpClientContext.create(), handler); Boolean wasItOk3 = futureTask3.get(10, TimeUnit.SECONDS); System.out.println("It was ok? " + wasItOk3); FutureCallback<Boolean> callback = new FutureCallback<Boolean>() { public void completed(Boolean result) { System.out.println("completed with " + result); } public void failed(Exception ex) { System.out.println("failed with " + ex.getMessage()); } public void cancelled() { System.out.println("cancelled"); } }; // Simple request with a callback HttpGet request4 = new HttpGet("http://google.com"); // using a null HttpContext here since it is optional // the callback will be called when the task completes, fails, or is cancelled HttpRequestFutureTask<Boolean> futureTask4 = requestExecService.execute(request4, HttpClientContext.create(), handler, callback); Boolean wasItOk4 = futureTask4.get(10, TimeUnit.SECONDS); System.out.println("It was ok? " + wasItOk4); } finally { requestExecService.close(); } }
From source file:interoperabilite.webservice.client.ClientWithRequestFuture.java
public static void main(String[] args) throws Exception { // the simplest way to create a HttpAsyncClientWithFuture HttpClient httpclient = HttpClientBuilder.create().setMaxConnPerRoute(5).setMaxConnTotal(5).build(); ExecutorService execService = Executors.newFixedThreadPool(5); FutureRequestExecutionService requestExecService = new FutureRequestExecutionService(httpclient, execService);/*from www . j a v a2 s. com*/ try { // Because things are asynchronous, you must provide a ResponseHandler ResponseHandler<Boolean> handler = new ResponseHandler<Boolean>() { @Override public Boolean handleResponse(HttpResponse response) throws ClientProtocolException, IOException { // simply return true if the status was OK return response.getStatusLine().getStatusCode() == 200; } }; // Simple request ... HttpGet request1 = new HttpGet("http://httpbin.org/get"); HttpRequestFutureTask<Boolean> futureTask1 = requestExecService.execute(request1, HttpClientContext.create(), handler); Boolean wasItOk1 = futureTask1.get(); System.out.println("It was ok? " + wasItOk1); // Cancel a request try { HttpGet request2 = new HttpGet("http://httpbin.org/get"); HttpRequestFutureTask<Boolean> futureTask2 = requestExecService.execute(request2, HttpClientContext.create(), handler); futureTask2.cancel(true); Boolean wasItOk2 = futureTask2.get(); System.out.println("It was cancelled so it should never print this: " + wasItOk2); } catch (CancellationException e) { System.out.println("We cancelled it, so this is expected"); } // Request with a timeout HttpGet request3 = new HttpGet("http://httpbin.org/get"); HttpRequestFutureTask<Boolean> futureTask3 = requestExecService.execute(request3, HttpClientContext.create(), handler); Boolean wasItOk3 = futureTask3.get(10, TimeUnit.SECONDS); System.out.println("It was ok? " + wasItOk3); FutureCallback<Boolean> callback = new FutureCallback<Boolean>() { @Override public void completed(Boolean result) { System.out.println("completed with " + result); } @Override public void failed(Exception ex) { System.out.println("failed with " + ex.getMessage()); } @Override public void cancelled() { System.out.println("cancelled"); } }; // Simple request with a callback HttpGet request4 = new HttpGet("http://httpbin.org/get"); // using a null HttpContext here since it is optional // the callback will be called when the task completes, fails, or is cancelled HttpRequestFutureTask<Boolean> futureTask4 = requestExecService.execute(request4, HttpClientContext.create(), handler, callback); Boolean wasItOk4 = futureTask4.get(10, TimeUnit.SECONDS); System.out.println("It was ok? " + wasItOk4); } finally { requestExecService.close(); } }
From source file:db.Db.java
public static void main(String[] args) throws InterruptedException, Exception { // TODO code application logic here //SETUP//ww w. j a va 2 s. c om WebDriver driver; String referralUrl, accounts[][]; String mSuffix = new String(); double space = 0, nAccounts; int needAccounts, creAccounts, f; StringBuffer verificationErrors = new StringBuffer(); driver = new FirefoxDriver(); // driver = new HtmlUnitDriver(); driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS); referralUrl = "https://www.dropbox.com/referrals/NTM2OTAyMjIyMjk?src=global9"; mSuffix = "@gmail.com"; space = 16.250; space = (Math.floor(space * 2) / 2); //trunk number to .0 or .5 needAccounts = (int) ((18 - space) * 2); //number of accounts needed creAccounts = 0; //number of accounts created accounts = new String[needAccounts][4]; //accounts credentials matrix //GENERATE ACCOUNTS for (f = 0; f < accounts.length; f++) genAccount(accounts, mSuffix, f); //REGISTER int regAttempts = 0; System.out.print("Registering accounts => "); for (f = 0; f < accounts.length; f++) { while (!regAccount(accounts, referralUrl, f, driver) && regAttempts < 3) { regAttempts++; genAccount(accounts, mSuffix, f); } if (regAttempts < 3) creAccounts++; else System.out.println("Registration failed 3 consecutive times. Aborting"); } //end for if (creAccounts == needAccounts) System.out.println("\n" + creAccounts + " DROPBOX ACCOUNTS CREATED SUCCESFULLY!! :D :D"); //TEARDOWN driver.quit(); }
From source file:io.kahu.hawaii.util.call.example.Example2.java
public static final void main(String[] args) throws Exception { DOMConfigurator.configure(Example2.class.getResource("/log4j.xml").getFile()); RestServer server = null;// www . j ava 2s . c o m ExecutorRepository executorRepository = null; try { /* * Create our rest server with a 'ClientResource'. */ server = new RestServer(SERVER_PORT); server.addResource(ClientResource.class); server.start(); /* * START of generic setup */ // Create a log manager (purpose and explanation out of scope for this example). LogManager logManager = new DefaultLogManager(new LogManagerConfiguration(new LoggingConfiguration())); // Create an executor, which holds a queue with core size 1, max size 2, a queue of size 2. Threads 'outside the core pool' that are still active after one minute will get cleaned up. HawaiiExecutorImpl executor = new HawaiiExecutorImpl(ExecutorRepository.DEFAULT_EXECUTOR_NAME, 1, 2, 2, new TimeOut(1, TimeUnit.MINUTES), logManager); // Create an executor, which holds a queue with core size 1, max size 2, a queue of size 2. Threads 'outside the core pool' that are still active after one minute will get cleaned up. HawaiiExecutorImpl executor2 = new HawaiiExecutorImpl("crm", 1, 2, 2, new TimeOut(1, TimeUnit.MINUTES), logManager); // Create the repository that holds all executors executorRepository = new ExecutorRepository(logManager); executorRepository.add(executor); executorRepository.add(executor2); Map<String, String> defaultExecutors = new HashMap<>(); defaultExecutors.put("crm", "crm"); executorRepository.setDefaultExecutors(defaultExecutors); // Create a new request dispatcher. RequestDispatcher requestDispatcher = new RequestDispatcher(executorRepository, logManager); /* * END of generic setup */ /* * Setup the request (builder). */ HttpRequestContext<Person> context = new HttpRequestContext<>(HttpMethod.GET, "http://localhost:" + SERVER_PORT, "/client/{client-id}", "crm", "get_client_by_id", new TimeOut(10, TimeUnit.SECONDS)); CallLogger callLogger = new CallLoggerImpl<>(logManager, new HttpRequestLogger(), new JsonPayloadResponseLogger<Person>()); RequestPrototype<HttpResponse, Person> prototype = new RequestPrototype(requestDispatcher, context, new GetCustomerByIdResponseHandler(), callLogger); HttpRequestBuilder<Person> getPersonByIdRequest = new HttpRequestBuilder<>(prototype); /* * Use the request (builder). */ Request<Person> request = getPersonByIdRequest.newInstance().withPathVariables("10").build(); Person person = request.execute().get(); System.err.println("CLIENT - Got client '" + person.getName() + "' with id '" + person.getId() + "'."); } finally { server.stop(); if (executorRepository != null) { executorRepository.stop(); } } }
From source file:com.sun.grizzly.samples.http.embed.GrizzlyEmbedWebServer.java
public static void main(String args[]) throws Exception { String path = args[0];/* w w w . j av a 2 s .c o m*/ if (args[0] == null || path == null) { System.out.println("Invalid static resource path"); System.exit(-1); } GrizzlyWebServer ws = new GrizzlyWebServer(path); /* ws.enableJMX(new Management() { public void registerComponent(Object bean, ObjectName oname, String type) throws Exception{ Registry.getRegistry().registerComponent(bean,oname,type); } public void unregisterComponent(ObjectName oname) throws Exception{ Registry.getRegistry(). unregisterComponent(oname); } }); */ final Statistics stats = ws.getStatistics(); stats.startGatheringStatistics(); ste.scheduleAtFixedRate(new Runnable() { public void run() { System.out.println( "Current connected users: " + stats.getKeepAliveStatistics().getCountConnections()); System.out.println( "How many requests since startup:" + stats.getRequestStatistics().getRequestCount()); System.out.println("How many connection we queued because of all" + "thread were busy: " + stats.getThreadPoolStatistics().getCountQueued()); System.out.println("Max Open Connection: " + stats.getRequestStatistics().getMaxOpenConnections()); System.out.println("Request Queued (15min avg): " + stats.getThreadPoolStatistics().getCountQueued15MinuteAverage()); System.out.println( "Request Queued (total): " + stats.getThreadPoolStatistics().getCountTotalQueued()); System.out.println("Byte Sent: " + stats.getRequestStatistics().getBytesSent()); System.out.println("200 Count: " + stats.getRequestStatistics().getCount200()); System.out.println("404 Count: " + stats.getRequestStatistics().getCount404()); return; } }, 0, 10, TimeUnit.SECONDS); System.out.println("Grizzly WebServer listening on port 8080"); ws.start(); }
From source file:com.mgmtp.perfload.core.daemon.LtDaemon.java
public static void main(final String... args) { JCommander jCmd = null;/*from w w w.j a v a 2s . co m*/ try { LtDaemonArgs cliArgs = new LtDaemonArgs(); jCmd = new JCommander(cliArgs); jCmd.parse(args); log().info("Starting perfLoad Daemon..."); log().info(cliArgs.toString()); if (cliArgs.shutdown) { shutdownDaemon(cliArgs.port); System.exit(0); } // Client is expected next to the daemon File clientDir = new File(new File(System.getProperty("user.dir")).getParentFile(), "client"); ExecutorService execService = Executors.newCachedThreadPool(); StreamGobbler gobbler = new StreamGobbler(execService); Server server = new DefaultServer(cliArgs.port); LtDaemon daemon = new LtDaemon(clientDir, new ForkedProcessClientRunner(execService, gobbler), server); daemon.execute(); execService.shutdown(); execService.awaitTermination(10L, TimeUnit.SECONDS); System.exit(0); } catch (ParameterException ex) { jCmd.usage(); System.exit(1); } catch (Exception ex) { log().error(ex.getMessage(), ex); System.exit(-1); } }
From source file:accumulo.AccumuloStuff.java
public static void main(String[] args) throws Exception { File tmp = new File(System.getProperty("user.dir") + "/target/mac-test"); if (tmp.exists()) { FileUtils.deleteDirectory(tmp);//from w ww .j a v a2 s. com } tmp.mkdirs(); String passwd = "password"; MiniAccumuloConfigImpl cfg = new MiniAccumuloConfigImpl(tmp, passwd); cfg.setNumTservers(1); // cfg.useMiniDFS(true); final MiniAccumuloClusterImpl cluster = cfg.build(); setCoreSite(cluster); cluster.start(); ExecutorService svc = Executors.newFixedThreadPool(2); try { Connector conn = cluster.getConnector("root", passwd); String table = "table"; conn.tableOperations().create(table); final BatchWriter bw = conn.createBatchWriter(table, new BatchWriterConfig()); final AtomicBoolean flushed = new AtomicBoolean(false); Runnable writer = new Runnable() { @Override public void run() { try { Mutation m = new Mutation("row"); m.put("colf", "colq", "value"); bw.addMutation(m); bw.flush(); flushed.set(true); } catch (Exception e) { log.error("Got exception trying to flush mutation", e); } log.info("Exiting batchwriter thread"); } }; Runnable restarter = new Runnable() { @Override public void run() { try { for (ProcessReference proc : cluster.getProcesses().get(ServerType.TABLET_SERVER)) { cluster.killProcess(ServerType.TABLET_SERVER, proc); } cluster.exec(TabletServer.class); } catch (Exception e) { log.error("Caught exception restarting tabletserver", e); } log.info("Exiting restart thread"); } }; svc.execute(writer); svc.execute(restarter); log.info("Waiting for shutdown"); svc.shutdown(); if (!svc.awaitTermination(120, TimeUnit.SECONDS)) { log.info("Timeout on shutdown exceeded"); svc.shutdownNow(); } else { log.info("Cleanly shutdown"); log.info("Threadpool is terminated? " + svc.isTerminated()); } if (flushed.get()) { log.info("****** BatchWriter was flushed *********"); } else { log.info("****** BatchWriter was NOT flushed *********"); } bw.close(); log.info("Got record {}", Iterables.getOnlyElement(conn.createScanner(table, Authorizations.EMPTY))); } finally { cluster.stop(); } }
From source file:mcnutty.music.get.MusicGet.java
public static void main(String[] args) throws Exception { //print out music-get System.out.println(" _ _ "); System.out.println(" _ __ ___ _ _ ___(_) ___ __ _ ___| |_ "); System.out.println("| '_ ` _ \\| | | / __| |/ __|____ / _` |/ _ \\ __|"); System.out.println("| | | | | | |_| \\__ \\ | (_|_____| (_| | __/ |_ "); System.out.println("|_| |_| |_|\\__,_|___/_|\\___| \\__, |\\___|\\__|"); System.out.println(" |___/ \n"); //these will always be initialised later (but the compiler doesn't know that) String directory = ""; Properties prop = new Properties(); try (InputStream input = new FileInputStream("config.properties")) { prop.load(input);//from w w w . j a v a2 s . c om if (prop.getProperty("directory") != null) { directory = prop.getProperty("directory"); } else { System.out.println( "Error reading config property 'directory' - using default value of /tmp/musicserver/\n"); directory = "/tmp/musicserver/"; } if (prop.getProperty("password") == null) { System.out.println("Error reading config property 'password' - no default value, exiting\n"); System.exit(1); } } catch (IOException e) { System.out.println("Error reading config file"); System.exit(1); } //create a queue object ProcessQueue process_queue = new ProcessQueue(); try { if (args.length > 0 && args[0].equals("clean")) { Files.delete(Paths.get("queue.json")); } //load an existing queue if possible String raw_queue = Files.readAllLines(Paths.get("queue.json")).toString(); JSONArray queue_state = new JSONArray(raw_queue); ConcurrentLinkedQueue<QueueItem> loaded_queue = new ConcurrentLinkedQueue<>(); JSONArray queue = queue_state.getJSONArray(0); for (int i = 0; i < queue.length(); i++) { JSONObject item = ((JSONObject) queue.get(i)); QueueItem loaded_item = new QueueItem(); loaded_item.ip = item.getString("ip"); loaded_item.real_name = item.getString("name"); loaded_item.disk_name = item.getString("guid"); loaded_queue.add(loaded_item); } process_queue.bucket_queue = loaded_queue; System.out.println("Loaded queue from disk\n"); } catch (Exception ex) { //otherwise clean out the music directory and start a new queue try { Files.walkFileTree(Paths.get(directory), new SimpleFileVisitor<Path>() { @Override public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException { Files.delete(file); return FileVisitResult.CONTINUE; } }); Files.delete(Paths.get(directory)); } catch (Exception e) { e.printStackTrace(); } Files.createDirectory(Paths.get(directory)); System.out.println("Created a new queue\n"); } //start the web server StartServer start_server = new StartServer(process_queue, directory); new Thread(start_server).start(); //wit for the web server to spool up Thread.sleep(1000); //read items from the queue and play them while (true) { QueueItem next_item = process_queue.next_item(); if (!next_item.equals(new QueueItem())) { //Check the timeout int timeout = 547; try (FileInputStream input = new FileInputStream("config.properties")) { prop.load(input); timeout = Integer.parseInt(prop.getProperty("timeout", "547")); } catch (Exception e) { e.printStackTrace(); } System.out.println("Playing " + next_item.real_name); process_queue.set_played(next_item); process_queue.save_queue(); Process p = Runtime.getRuntime().exec("timeout " + timeout + "s mplayer -fs -quiet -af volnorm=2:0.25 " + directory + next_item.disk_name); try { p.waitFor(timeout, TimeUnit.SECONDS); Files.delete(Paths.get(directory + next_item.disk_name)); } catch (Exception e) { e.printStackTrace(); } } else { process_queue.bucket_played.clear(); } Thread.sleep(1000); } }
From source file:com.yahoo.pasc.paxos.client.PaxosClient.java
public static void main(String[] args) throws Exception { CommandLineParser parser = new PosixParser(); Options options;/*from ww w. jav a 2 s. c o m*/ { Option id = new Option("i", true, "client id"); Option clients = new Option("c", true, "number of clients"); Option host = new Option("l", true, "leader (hostname:port)"); Option servers = new Option("s", true, "number of servers"); Option quorum = new Option("q", true, "necesarry quorum at the client"); Option port = new Option("p", true, "port used by client"); Option buffer = new Option("b", true, "number of concurrent clients"); Option timeout = new Option("t", true, "timeout in milliseconds"); Option udp = new Option("u", false, "use UDP"); Option zookeeper = new Option("z", true, "zookeeper connection string"); Option warmup = new Option("w", true, "warmup messagges"); Option measuring = new Option("m", true, "measuring time"); Option request = new Option("r", true, "request size"); Option frequency = new Option("f", true, "frequency of throughput info"); Option anm = new Option("a", false, "use protection"); Option inlineThresh = new Option("n", true, "threshold for sending requests iNline with accepts "); Option asynSize = new Option("y", true, "size of async messages queue"); options = new Options(); options.addOption(id).addOption(host).addOption(servers).addOption(quorum).addOption(port) .addOption(warmup).addOption(buffer).addOption(timeout).addOption(udp).addOption(zookeeper) .addOption(clients).addOption(measuring).addOption(request).addOption(frequency).addOption(anm) .addOption(inlineThresh).addOption(asynSize); } CommandLine line = null; try { line = parser.parse(options, args); String host = line.hasOption('l') ? line.getOptionValue('l') : "localhost:20548,localhost:20748,localhost:20778"; String zkConnection = line.hasOption('z') ? line.getOptionValue('z') : "localhost:2181"; int clientIds = line.hasOption('i') ? Integer.parseInt(line.getOptionValue('i')) : 0; int servers = line.hasOption('s') ? Integer.parseInt(line.getOptionValue('s')) : 3; int quorum = line.hasOption('q') ? Integer.parseInt(line.getOptionValue('q')) : 1; int buffer = line.hasOption('b') ? Integer.parseInt(line.getOptionValue('b')) : 1; int timeout = line.hasOption('t') ? Integer.parseInt(line.getOptionValue('t')) : 5000; int clients = line.hasOption('c') ? Integer.parseInt(line.getOptionValue('c')) : 1; int requestSize = line.hasOption('r') ? Integer.parseInt(line.getOptionValue('r')) : 0; int inlineThreshold = line.hasOption('n') ? Integer.parseInt(line.getOptionValue('n')) : 1000; int asynSize = line.hasOption('y') ? Integer.parseInt(line.getOptionValue('y')) : 100; boolean protection = line.hasOption('a'); int threads = Runtime.getRuntime().availableProcessors() * 2; final ExecutionHandler executor = new ExecutionHandler(new OrderedMemoryAwareThreadPoolExecutor(threads, 1024 * 1024, 1024 * 1024 * 1024, 30, TimeUnit.SECONDS, Executors.defaultThreadFactory())); String[] serverHosts = host.split(","); ServerHelloHandler shello = new ServerHelloHandler(); ReplyHandler reply = new ReplyHandler(); SubmitHandler submit = new SubmitHandler(); TimeoutHandler tout = new TimeoutHandler(); AsyncMessageHandler asyncm = new AsyncMessageHandler(); ByeHandler bye = new ByeHandler(); HelloHandler hello = new HelloHandler(); Random rnd = new Random(); for (int i = 0; i < buffer; ++i) { ClientState clientState = new ClientState(servers, quorum, inlineThreshold, asynSize); final PascRuntime<ClientState> runtime = new PascRuntime<ClientState>(protection); runtime.setState(clientState); runtime.addHandler(ServerHello.class, shello); runtime.addHandler(Reply.class, reply); runtime.addHandler(Submit.class, submit); runtime.addHandler(Timeout.class, tout); runtime.addHandler(AsyncMessage.class, asyncm); runtime.addHandler(Bye.class, bye); runtime.addHandler(Hello.class, hello); final PaxosClientHandler handler = new PaxosClientHandler(runtime, new SimpleClient(requestSize), serverHosts, clients, timeout, zkConnection, executor); if (line.hasOption('w')) handler.setWarmup(Integer.parseInt(line.getOptionValue('w'))); if (line.hasOption('m')) handler.setMeasuringTime(Integer.parseInt(line.getOptionValue('m'))); if (line.hasOption('f')) handler.setPeriod(Integer.parseInt(line.getOptionValue('f'))); handler.start(); Thread.sleep(rnd.nextInt(200)); } } catch (Exception e) { System.err.println("Unexpected exception " + e); e.printStackTrace(); HelpFormatter formatter = new HelpFormatter(); formatter.printHelp("Paxos", options); System.exit(-1); } }