List of usage examples for java.lang Thread start
public synchronized void start()
From source file:com.github.ambry.store.DiskReformatter.java
public static void main(String[] args) throws Exception { VerifiableProperties properties = ToolUtils.getVerifiableProperties(args); DiskReformatterConfig config = new DiskReformatterConfig(properties); StoreConfig storeConfig = new StoreConfig(properties); ClusterMapConfig clusterMapConfig = new ClusterMapConfig(properties); ServerConfig serverConfig = new ServerConfig(properties); ClusterAgentsFactory clusterAgentsFactory = Utils.getObj(clusterMapConfig.clusterMapClusterAgentsFactory, clusterMapConfig, config.hardwareLayoutFilePath, config.partitionLayoutFilePath); try (ClusterMap clusterMap = clusterAgentsFactory.getClusterMap()) { StoreKeyConverterFactory storeKeyConverterFactory = Utils.getObj( serverConfig.serverStoreKeyConverterFactory, properties, clusterMap.getMetricRegistry()); StoreKeyFactory storeKeyFactory = Utils.getObj(storeConfig.storeKeyFactory, clusterMap); DataNodeId dataNodeId = clusterMap.getDataNodeId(config.datanodeHostname, config.datanodePort); if (dataNodeId == null) { throw new IllegalArgumentException("Did not find node in clustermap with hostname:port - " + config.datanodeHostname + ":" + config.datanodePort); }/*from w w w .ja v a2 s . c om*/ DiskReformatter reformatter = new DiskReformatter(dataNodeId, Collections.EMPTY_LIST, config.fetchSizeInBytes, storeConfig, storeKeyFactory, clusterMap, SystemTime.getInstance(), storeKeyConverterFactory.getStoreKeyConverter()); AtomicInteger exitStatus = new AtomicInteger(0); CountDownLatch latch = new CountDownLatch(config.diskMountPaths.length); for (int i = 0; i < config.diskMountPaths.length; i++) { int finalI = i; Runnable runnable = () -> { try { reformatter.reformat(config.diskMountPaths[finalI], new File(config.scratchPaths[finalI])); latch.countDown(); } catch (Exception e) { throw new IllegalStateException(e); } }; Thread thread = Utils.newThread(config.diskMountPaths[finalI] + "-reformatter", runnable, true); thread.setUncaughtExceptionHandler((t, e) -> { exitStatus.set(1); logger.error("Reformatting {} failed", config.diskMountPaths[finalI], e); latch.countDown(); }); thread.start(); } latch.await(); System.exit(exitStatus.get()); } }
From source file:ffx.numerics.fft.Real3DCuda.java
/** * <p>// ww w .j a v a2 s. com * main</p> * * @param args an array of {@link java.lang.String} objects. * @throws java.lang.Exception if any. */ public static void main(String[] args) throws Exception { int dimNotFinal = 64; int reps = 10; if (args != null) { try { dimNotFinal = Integer.parseInt(args[0]); if (dimNotFinal < 1) { dimNotFinal = 64; } reps = Integer.parseInt(args[1]); if (reps < 1) { reps = 5; } } catch (Exception e) { } } if (dimNotFinal % 2 != 0) { dimNotFinal++; } final int dim = dimNotFinal; System.out.println(String.format( "Initializing a %d cubed grid.\n" + "The best timing out of %d repititions will be used.", dim, reps)); final int dimCubed = dim * dim * dim; final int dimCubed2 = (dim + 2) * dim * dim; /** * Create an array to save the initial input and result. */ final double orig[] = new double[dimCubed2]; final double answer[] = new double[dimCubed2]; final double data[] = new double[dimCubed2]; final double recip[] = new double[dimCubed]; final float origf[] = new float[dimCubed2]; final float dataf[] = new float[dimCubed2]; final float recipf[] = new float[dimCubed]; Random randomNumberGenerator = new Random(1); int index = 0; int index2 = 0; /** * Row-major order. */ for (int x = 0; x < dim; x++) { for (int y = 0; y < dim; y++) { for (int z = 0; z < dim; z++) { float randomNumber = randomNumberGenerator.nextFloat(); orig[index] = randomNumber; origf[index] = randomNumber; index++; recip[index2] = 1.0; recipf[index2] = 1.0f; index2++; } // Padding index += 2; } } Real3D real3D = new Real3D(dim, dim, dim); Real3DParallel real3DParallel = new Real3DParallel(dim, dim, dim, new ParallelTeam(), IntegerSchedule.fixed()); Real3DCuda real3DCUDA = new Real3DCuda(dim, dim, dim, dataf, recipf); Thread cudaThread = new Thread(real3DCUDA); cudaThread.setPriority(Thread.MAX_PRIORITY); cudaThread.start(); double toSeconds = 0.000000001; long parTime = Long.MAX_VALUE; long seqTime = Long.MAX_VALUE; long clTime = Long.MAX_VALUE; real3D.setRecip(recip); for (int i = 0; i < reps; i++) { System.arraycopy(orig, 0, data, 0, dimCubed2); long time = System.nanoTime(); real3D.convolution(data); time = (System.nanoTime() - time); System.out.println(String.format("%2d Sequential: %8.3f", i + 1, toSeconds * time)); if (time < seqTime) { seqTime = time; } } System.arraycopy(data, 0, answer, 0, dimCubed2); real3DParallel.setRecip(recip); for (int i = 0; i < reps; i++) { System.arraycopy(orig, 0, data, 0, dimCubed2); long time = System.nanoTime(); real3DParallel.convolution(data); time = (System.nanoTime() - time); System.out.println(String.format("%2d Parallel: %8.3f", i + 1, toSeconds * time)); if (time < parTime) { parTime = time; } } double maxError = Double.MIN_VALUE; double rmse = 0.0; index = 0; for (int x = 0; x < dim; x++) { for (int y = 0; y < dim; y++) { for (int z = 0; z < dim; z++) { double error = Math.abs((orig[index] - data[index] / dimCubed)); if (error > maxError) { maxError = error; } rmse += error * error; index++; } index += 2; } } rmse /= dimCubed; rmse = Math.sqrt(rmse); logger.info(String.format("Parallel RMSE: %12.10f, Max: %12.10f", rmse, maxError)); for (int i = 0; i < reps; i++) { System.arraycopy(origf, 0, dataf, 0, dimCubed2); long time = System.nanoTime(); real3DCUDA.convolution(dataf); time = (System.nanoTime() - time); System.out.println(String.format("%2d CUDA: %8.3f", i + 1, toSeconds * time)); if (time < clTime) { clTime = time; } } real3DCUDA.free(); real3DCUDA = null; maxError = Double.MIN_VALUE; double avg = 0.0; rmse = 0.0; index = 0; for (int x = 0; x < dim; x++) { for (int y = 0; y < dim; y++) { for (int z = 0; z < dim; z++) { if (Float.isNaN(dataf[index])) { logger.info(String.format("Not a number %d %d %d", x, y, z)); System.exit(-1); } double error = Math.abs(origf[index] - dataf[index]); avg += error; if (error > maxError) { maxError = error; } rmse += error * error; index++; } index += 2; } } rmse /= dimCubed; avg /= dimCubed; rmse = Math.sqrt(rmse); logger.info(String.format("CUDA RMSE: %12.10f, Max: %12.10f, Avg: %12.10f", rmse, maxError, avg)); System.out.println(String.format("Best Sequential Time: %8.3f", toSeconds * seqTime)); System.out.println(String.format("Best Parallel Time: %8.3f", toSeconds * parTime)); System.out.println(String.format("Best CUDA Time: %8.3f", toSeconds * clTime)); System.out.println(String.format("Parallel Speedup: %15.5f", (double) seqTime / parTime)); System.out.println(String.format("CUDA Speedup: %15.5f", (double) seqTime / clTime)); }
From source file:com.oltpbenchmark.multitenancy.MuTeBench.java
/** * @param args/*from ww w. j a v a 2s . c o m*/ * @throws Exception */ public static void main(String[] args) throws Exception { String duration = null; String scenarioFile = null; // ------------------------------------------------------------------- // INITIALIZE LOGGING // ------------------------------------------------------------------- String log4jPath = System.getProperty("log4j.configuration"); if (log4jPath != null) { org.apache.log4j.PropertyConfigurator.configure(log4jPath); } else { throw new RuntimeException("Missing log4j.properties file"); } // ------------------------------------------------------------------- // PARSE COMMAND LINE PARAMETERS // ------------------------------------------------------------------- CommandLineParser parser = new PosixParser(); XMLConfiguration pluginConfig = null; try { pluginConfig = new XMLConfiguration("config/plugin.xml"); } catch (ConfigurationException e1) { LOG.info("Plugin configuration file config/plugin.xml is missing"); e1.printStackTrace(); } pluginConfig.setExpressionEngine(new XPathExpressionEngine()); Options options = new Options(); options.addOption("s", "scenario", true, "[required] Workload scenario file"); options.addOption("a", "analysis-buckets", true, "sampling buckets for result aggregation"); options.addOption("r", "runtime", true, "maximum runtime (no events will be started after finishing runtime)"); options.addOption("v", "verbose", false, "Display Messages"); options.addOption("g", "gui", false, "Show controlling GUI"); options.addOption("h", "help", false, "Print this help"); options.addOption("o", "output", true, "Output file (default System.out)"); options.addOption("b", "baseline", true, "Output files of previous baseline run"); options.addOption(null, "histograms", false, "Print txn histograms"); options.addOption("d", "dialects-export", true, "Export benchmark SQL to a dialects file"); // parse the command line arguments CommandLine argsLine = parser.parse(options, args); if (argsLine.hasOption("h")) { printUsage(options); return; } else if (!argsLine.hasOption("scenario")) { INIT_LOG.fatal("Missing scenario description file"); System.exit(-1); } else scenarioFile = argsLine.getOptionValue("scenario"); if (argsLine.hasOption("r")) duration = argsLine.getOptionValue("r"); if (argsLine.hasOption("runtime")) duration = argsLine.getOptionValue("runtime"); // ------------------------------------------------------------------- // CREATE TENANT SCHEDULE // ------------------------------------------------------------------- INIT_LOG.info("Create schedule"); Schedule schedule = new Schedule(duration, scenarioFile); HashMap<Integer, ScheduleEvents> tenantEvents = schedule.getTenantEvents(); ArrayList<Integer> tenantList = schedule.getTenantList(); List<BenchmarkModule> benchList = new ArrayList<BenchmarkModule>(); for (int tenInd = 0; tenInd < tenantList.size(); tenInd++) { int tenantID = tenantList.get(tenInd); for (int tenEvent = 0; tenEvent < tenantEvents.get(tenantID).size(); tenEvent++) { BenchmarkSettings benchmarkSettings = (BenchmarkSettings) tenantEvents.get(tenantID) .getBenchmarkSettings(tenEvent); // update benchmark Settings benchmarkSettings.setTenantID(tenantID); // ------------------------------------------------------------------- // GET PLUGIN LIST // ------------------------------------------------------------------- String plugins = benchmarkSettings.getBenchmark(); String[] pluginList = plugins.split(","); String configFile = benchmarkSettings.getConfigFile(); XMLConfiguration xmlConfig = new XMLConfiguration(configFile); xmlConfig.setExpressionEngine(new XPathExpressionEngine()); int lastTxnId = 0; for (String plugin : pluginList) { // ---------------------------------------------------------------- // WORKLOAD CONFIGURATION // ---------------------------------------------------------------- String pluginTest = ""; pluginTest = "[@bench='" + plugin + "']"; WorkloadConfiguration wrkld = new WorkloadConfiguration(); wrkld.setTenantId(tenantID); wrkld.setBenchmarkName(setTenantIDinString(plugin, tenantID)); wrkld.setXmlConfig(xmlConfig); wrkld.setDBType(DatabaseType.get(setTenantIDinString(xmlConfig.getString("dbtype"), tenantID))); wrkld.setDBDriver(setTenantIDinString(xmlConfig.getString("driver"), tenantID)); wrkld.setDBConnection(setTenantIDinString(xmlConfig.getString("DBUrl"), tenantID)); wrkld.setDBName(setTenantIDinString(xmlConfig.getString("DBName"), tenantID)); wrkld.setDBUsername(setTenantIDinString(xmlConfig.getString("username"), tenantID)); wrkld.setDBPassword(setTenantIDinString(xmlConfig.getString("password"), tenantID)); String terminalString = setTenantIDinString(xmlConfig.getString("terminals[not(@bench)]", "0"), tenantID); int terminals = Integer.parseInt(xmlConfig.getString("terminals" + pluginTest, terminalString)); wrkld.setTerminals(terminals); int taSize = Integer.parseInt(xmlConfig.getString("taSize", "1")); if (taSize < 0) INIT_LOG.fatal("taSize must not be negative!"); wrkld.setTaSize(taSize); wrkld.setProprietaryTaSyntax(xmlConfig.getBoolean("proprietaryTaSyntax", false)); wrkld.setIsolationMode(setTenantIDinString( xmlConfig.getString("isolation", "TRANSACTION_SERIALIZABLE"), tenantID)); wrkld.setScaleFactor(Double .parseDouble(setTenantIDinString(xmlConfig.getString("scalefactor", "1.0"), tenantID))); wrkld.setRecordAbortMessages(xmlConfig.getBoolean("recordabortmessages", false)); int size = xmlConfig.configurationsAt("/works/work").size(); for (int i = 1; i < size + 1; i++) { SubnodeConfiguration work = xmlConfig.configurationAt("works/work[" + i + "]"); List<String> weight_strings; // use a workaround if there multiple workloads or // single // attributed workload if (pluginList.length > 1 || work.containsKey("weights[@bench]")) { weight_strings = get_weights(plugin, work); } else { weight_strings = work.getList("weights[not(@bench)]"); } int rate = 1; boolean rateLimited = true; boolean disabled = false; // can be "disabled", "unlimited" or a number String rate_string; rate_string = setTenantIDinString(work.getString("rate[not(@bench)]", ""), tenantID); rate_string = setTenantIDinString(work.getString("rate" + pluginTest, rate_string), tenantID); if (rate_string.equals(RATE_DISABLED)) { disabled = true; } else if (rate_string.equals(RATE_UNLIMITED)) { rateLimited = false; } else if (rate_string.isEmpty()) { LOG.fatal(String.format( "Tenant " + tenantID + ": Please specify the rate for phase %d and workload %s", i, plugin)); System.exit(-1); } else { try { rate = Integer.parseInt(rate_string); if (rate < 1) { LOG.fatal("Tenant " + tenantID + ": Rate limit must be at least 1. Use unlimited or disabled values instead."); System.exit(-1); } } catch (NumberFormatException e) { LOG.fatal(String.format( "Tenant " + tenantID + ": Rate string must be '%s', '%s' or a number", RATE_DISABLED, RATE_UNLIMITED)); System.exit(-1); } } Phase.Arrival arrival = Phase.Arrival.REGULAR; String arrive = setTenantIDinString(work.getString("@arrival", "regular"), tenantID); if (arrive.toUpperCase().equals("POISSON")) arrival = Phase.Arrival.POISSON; int activeTerminals; activeTerminals = Integer.parseInt(setTenantIDinString( work.getString("active_terminals[not(@bench)]", String.valueOf(terminals)), tenantID)); activeTerminals = Integer.parseInt(setTenantIDinString( work.getString("active_terminals" + pluginTest, String.valueOf(activeTerminals)), tenantID)); if (activeTerminals > terminals) { LOG.fatal("Tenant " + tenantID + ": Configuration error in work " + i + ": number of active terminals" + "" + "is bigger than the total number of terminals"); System.exit(-1); } wrkld.addWork(Integer.parseInt(setTenantIDinString(work.getString("/time"), tenantID)), rate, weight_strings, rateLimited, disabled, activeTerminals, arrival); } // FOR int numTxnTypes = xmlConfig .configurationsAt("transactiontypes" + pluginTest + "/transactiontype").size(); if (numTxnTypes == 0 && pluginList.length == 1) { // if it is a single workload run, <transactiontypes /> // w/o attribute is used pluginTest = "[not(@bench)]"; numTxnTypes = xmlConfig .configurationsAt("transactiontypes" + pluginTest + "/transactiontype").size(); } wrkld.setNumTxnTypes(numTxnTypes); // CHECKING INPUT PHASES int j = 0; for (Phase p : wrkld.getAllPhases()) { j++; if (p.getWeightCount() != wrkld.getNumTxnTypes()) { LOG.fatal(String.format("Tenant " + tenantID + ": Configuration files is inconsistent, phase %d contains %d weights but you defined %d transaction types", j, p.getWeightCount(), wrkld.getNumTxnTypes())); System.exit(-1); } } // FOR // Generate the dialect map wrkld.init(); assert (wrkld.getNumTxnTypes() >= 0); assert (xmlConfig != null); // ---------------------------------------------------------------- // BENCHMARK MODULE // ---------------------------------------------------------------- String classname = pluginConfig.getString("/plugin[@name='" + plugin + "']"); if (classname == null) { throw new ParseException("Plugin " + plugin + " is undefined in config/plugin.xml"); } BenchmarkModule bench = ClassUtil.newInstance(classname, new Object[] { wrkld }, new Class<?>[] { WorkloadConfiguration.class }); assert (benchList.get(0) != null); Map<String, Object> initDebug = new ListOrderedMap<String, Object>(); initDebug.put("Benchmark", String.format("%s {%s}", plugin.toUpperCase(), classname)); initDebug.put("Configuration", configFile); initDebug.put("Type", wrkld.getDBType()); initDebug.put("Driver", wrkld.getDBDriver()); initDebug.put("URL", wrkld.getDBConnection()); initDebug.put("Isolation", setTenantIDinString( xmlConfig.getString("isolation", "TRANSACTION_SERIALIZABLE [DEFAULT]"), tenantID)); initDebug.put("Scale Factor", wrkld.getScaleFactor()); INIT_LOG.info(SINGLE_LINE + "\n\n" + StringUtil.formatMaps(initDebug)); INIT_LOG.info(SINGLE_LINE); // Load TransactionTypes List<TransactionType> ttypes = new ArrayList<TransactionType>(); // Always add an INVALID type for Carlo ttypes.add(TransactionType.INVALID); int txnIdOffset = lastTxnId; for (int i = 1; i < wrkld.getNumTxnTypes() + 1; i++) { String key = "transactiontypes" + pluginTest + "/transactiontype[" + i + "]"; String txnName = setTenantIDinString(xmlConfig.getString(key + "/name"), tenantID); int txnId = i + 1; if (xmlConfig.containsKey(key + "/id")) { txnId = Integer .parseInt(setTenantIDinString(xmlConfig.getString(key + "/id"), tenantID)); } ttypes.add(bench.initTransactionType(txnName, txnId + txnIdOffset)); lastTxnId = i; } // FOR TransactionTypes tt = new TransactionTypes(ttypes); wrkld.setTransTypes(tt); if (benchmarkSettings.getBenchmarkSlaFile() != null) wrkld.setSlaFromFile(benchmarkSettings.getBenchmarkSlaFile()); LOG.debug("Tenant " + tenantID + ": Using the following transaction types: " + tt); bench.setTenantOffset(tenantEvents.get(tenantID).getTime(tenEvent)); bench.setTenantID(tenantID); bench.setBenchmarkSettings(benchmarkSettings); benchList.add(bench); } } } // create result collector ResultCollector rCollector = new ResultCollector(tenantList); // execute benchmarks in parallel ArrayList<Thread> benchThreads = new ArrayList<Thread>(); for (BenchmarkModule benchmark : benchList) { BenchmarkExecutor benchThread = new BenchmarkExecutor(benchmark, argsLine); Thread t = new Thread(benchThread); t.start(); benchThreads.add(t); benchmark.getWorkloadConfiguration().setrCollector(rCollector); } // waiting for completion of all benchmarks for (Thread t : benchThreads) { t.join(); } // print statistics int analysisBuckets = -1; if (argsLine.hasOption("analysis-buckets")) analysisBuckets = Integer.parseInt(argsLine.getOptionValue("analysis-buckets")); String output = null; if (argsLine.hasOption("o")) output = argsLine.getOptionValue("o"); String baseline = null; if (argsLine.hasOption("b")) baseline = argsLine.getOptionValue("b"); rCollector.printStatistics(output, analysisBuckets, argsLine.hasOption("histograms"), baseline); // create GUI if (argsLine.hasOption("g") && (!rCollector.getAllResults().isEmpty())) { try { Gui gui = new Gui(Integer.parseInt(argsLine.getOptionValue("analysis-buckets", "10")), rCollector, output); } catch (Exception e) { e.printStackTrace(); } } }
From source file:com.rabbitmq.examples.MulticastMain.java
public static void main(String[] args) { Options options = getOptions();/* ww w . j a v a 2 s . c o m*/ CommandLineParser parser = new GnuParser(); try { CommandLine cmd = parser.parse(options, args); if (cmd.hasOption('?')) { usage(options); System.exit(0); } String exchangeType = strArg(cmd, 't', "direct"); String exchangeName = strArg(cmd, 'e', exchangeType); String queueName = strArg(cmd, 'u', ""); int samplingInterval = intArg(cmd, 'i', 1); int rateLimit = intArg(cmd, 'r', 0); int producerCount = intArg(cmd, 'x', 1); int consumerCount = intArg(cmd, 'y', 1); int producerTxSize = intArg(cmd, 'm', 0); int consumerTxSize = intArg(cmd, 'n', 0); long confirm = intArg(cmd, 'c', -1); boolean autoAck = cmd.hasOption('a'); int prefetchCount = intArg(cmd, 'q', 0); int minMsgSize = intArg(cmd, 's', 0); int timeLimit = intArg(cmd, 'z', 0); List<?> flags = lstArg(cmd, 'f'); int frameMax = intArg(cmd, 'M', 0); int heartbeat = intArg(cmd, 'b', 0); String uri = strArg(cmd, 'h', "amqp://localhost"); boolean exclusive = "".equals(queueName); boolean autoDelete = !exclusive; //setup String id = UUID.randomUUID().toString(); Stats stats = new Stats(1000L * samplingInterval); ConnectionFactory factory = new ConnectionFactory(); factory.setUri(uri); factory.setRequestedFrameMax(frameMax); factory.setRequestedHeartbeat(heartbeat); Thread[] consumerThreads = new Thread[consumerCount]; Connection[] consumerConnections = new Connection[consumerCount]; for (int i = 0; i < consumerCount; i++) { System.out.println("starting consumer #" + i); Connection conn = factory.newConnection(); consumerConnections[i] = conn; Channel channel = conn.createChannel(); if (consumerTxSize > 0) channel.txSelect(); channel.exchangeDeclare(exchangeName, exchangeType); String qName = channel .queueDeclare(queueName, flags.contains("persistent"), exclusive, autoDelete, null) .getQueue(); if (prefetchCount > 0) channel.basicQos(prefetchCount); channel.queueBind(qName, exchangeName, id); Thread t = new Thread(new Consumer(channel, id, qName, consumerTxSize, autoAck, stats, timeLimit)); consumerThreads[i] = t; t.start(); } Thread[] producerThreads = new Thread[producerCount]; Connection[] producerConnections = new Connection[producerCount]; Channel[] producerChannels = new Channel[producerCount]; for (int i = 0; i < producerCount; i++) { System.out.println("starting producer #" + i); Connection conn = factory.newConnection(); producerConnections[i] = conn; Channel channel = conn.createChannel(); producerChannels[i] = channel; if (producerTxSize > 0) channel.txSelect(); if (confirm >= 0) channel.confirmSelect(); channel.exchangeDeclare(exchangeName, exchangeType); final Producer p = new Producer(channel, exchangeName, id, flags, producerTxSize, 1000L * samplingInterval, rateLimit, minMsgSize, timeLimit, confirm); channel.addReturnListener(p); channel.addConfirmListener(p); Thread t = new Thread(p); producerThreads[i] = t; t.start(); } for (int i = 0; i < producerCount; i++) { producerThreads[i].join(); producerChannels[i].clearReturnListeners(); producerChannels[i].clearConfirmListeners(); producerConnections[i].close(); } for (int i = 0; i < consumerCount; i++) { consumerThreads[i].join(); consumerConnections[i].close(); } } catch (ParseException exp) { System.err.println("Parsing failed. Reason: " + exp.getMessage()); usage(options); } catch (Exception e) { System.err.println("Main thread caught exception: " + e); e.printStackTrace(); System.exit(1); } }
From source file:framework.httpclient.nio.NHttpClient.java
public static void main(String[] args) throws Exception { // Create HTTP protocol processing chain HttpProcessor httpproc = HttpProcessorBuilder.create() // Use standard client-side protocol interceptors .add(new RequestContent()).add(new RequestTargetHost()).add(new RequestConnControl()) .add(new RequestUserAgent("LinkedHashSetVsTreeSet/1.1")).add(new RequestExpectContinue(true)) .build();/*from w w w .ja va 2 s .co m*/ // Create client-side HTTP protocol handler HttpAsyncRequestExecutor protocolHandler = new HttpAsyncRequestExecutor(); // Create client-side I/O event dispatch // IO final IOEventDispatch ioEventDispatch = new DefaultHttpClientIODispatch(protocolHandler, ConnectionConfig.DEFAULT); // Create client-side I/O reactor // IO reactor final ConnectingIOReactor ioReactor = new DefaultConnectingIOReactor(); // Create HTTP connection pool // HTTP BasicNIOConnPool pool = new BasicNIOConnPool(ioReactor, ConnectionConfig.DEFAULT); // Limit total number of connections to just two pool.setDefaultMaxPerRoute(2); pool.setMaxTotal(2); // Run the I/O reactor in a separate thread Thread t = new Thread(new Runnable() { public void run() { try { // Ready to go! ioReactor.execute(ioEventDispatch); } catch (InterruptedIOException ex) { System.err.println("Interrupted"); } catch (IOException e) { System.err.println("I/O error: " + e.getMessage()); } System.out.println("Shutdown"); } }); // Start the client thread t.start(); // Create HTTP requester // HTTP HttpAsyncRequester requester = new HttpAsyncRequester(httpproc); // Execute HTTP GETs to the following hosts and HttpHost[] targets = new HttpHost[] { new HttpHost("www.baidu.org", -1, "https"), // new HttpHost("www.zhihu.com", -1, "https"), new HttpHost("www.bilibili.com", -1, "https") }; final CountDownLatch latch = new CountDownLatch(targets.length); for (final HttpHost target : targets) { BasicHttpRequest request = new BasicHttpRequest("GET", "/"); HttpCoreContext coreContext = HttpCoreContext.create(); requester.execute(new BasicAsyncRequestProducer(target, request), new BasicAsyncResponseConsumer(), pool, coreContext, // Handle HTTP response from a callback new FutureCallback<HttpResponse>() { public void completed(final HttpResponse response) { latch.countDown(); System.out.println(target + "->" + response.getStatusLine()); } public void failed(final Exception ex) { latch.countDown(); System.err.println(target + "->" + ex); ex.printStackTrace(); } public void cancelled() { latch.countDown(); System.out.println(target + " cancelled"); } }); } latch.await(); System.out.println("Shutting down I/O reactor"); ioReactor.shutdown(); System.out.println("Done"); }
From source file:NHttpClient.java
public static void main(String[] args) throws Exception { HttpParams params = new BasicHttpParams(); params.setIntParameter(CoreConnectionPNames.SO_TIMEOUT, 5000) .setIntParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, 10000) .setIntParameter(CoreConnectionPNames.SOCKET_BUFFER_SIZE, 8 * 1024) .setBooleanParameter(CoreConnectionPNames.STALE_CONNECTION_CHECK, false) .setBooleanParameter(CoreConnectionPNames.TCP_NODELAY, true) .setParameter(CoreProtocolPNames.USER_AGENT, "HttpComponents/1.1"); final ConnectingIOReactor ioReactor = new DefaultConnectingIOReactor(2, params); BasicHttpProcessor httpproc = new BasicHttpProcessor(); httpproc.addInterceptor(new RequestContent()); httpproc.addInterceptor(new RequestTargetHost()); httpproc.addInterceptor(new RequestConnControl()); httpproc.addInterceptor(new RequestUserAgent()); httpproc.addInterceptor(new RequestExpectContinue()); // We are going to use this object to synchronize between the // I/O event and main threads CountDownLatch requestCount = new CountDownLatch(3); BufferingHttpClientHandler handler = new BufferingHttpClientHandler(httpproc, new MyHttpRequestExecutionHandler(requestCount), new DefaultConnectionReuseStrategy(), params); handler.setEventListener(new EventLogger()); final IOEventDispatch ioEventDispatch = new DefaultClientIOEventDispatch(handler, params); Thread t = new Thread(new Runnable() { public void run() { try { ioReactor.execute(ioEventDispatch); } catch (InterruptedIOException ex) { System.err.println("Interrupted"); } catch (IOException e) { System.err.println("I/O error: " + e.getMessage()); }/* www . j ava 2 s . co m*/ System.out.println("Shutdown"); } }); t.start(); SessionRequest[] reqs = new SessionRequest[3]; reqs[0] = ioReactor.connect(new InetSocketAddress("www.yahoo.com", 80), null, new HttpHost("www.yahoo.com"), new MySessionRequestCallback(requestCount)); reqs[1] = ioReactor.connect(new InetSocketAddress("www.google.com", 80), null, new HttpHost("www.google.ch"), new MySessionRequestCallback(requestCount)); reqs[2] = ioReactor.connect(new InetSocketAddress("www.apache.org", 80), null, new HttpHost("www.apache.org"), new MySessionRequestCallback(requestCount)); // Block until all connections signal // completion of the request execution requestCount.await(); System.out.println("Shutting down I/O reactor"); ioReactor.shutdown(); System.out.println("Done"); }
From source file:org.eclipse.ecf.provider.filetransfer.httpcore.NHttpClient.java
public static void main(String[] args) throws Exception { HttpParams params = new BasicHttpParams(); params.setIntParameter(CoreConnectionPNames.SO_TIMEOUT, 5000) .setIntParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, 10000) .setIntParameter(CoreConnectionPNames.SOCKET_BUFFER_SIZE, 8 * 1024) .setBooleanParameter(CoreConnectionPNames.STALE_CONNECTION_CHECK, false) .setBooleanParameter(CoreConnectionPNames.TCP_NODELAY, true) .setParameter(CoreProtocolPNames.USER_AGENT, "HttpComponents/1.1"); final ConnectingIOReactor ioReactor = new DefaultConnectingIOReactor(2, params); BasicHttpProcessor httpproc = new BasicHttpProcessor(); httpproc.addInterceptor(new RequestContent()); httpproc.addInterceptor(new RequestTargetHost()); httpproc.addInterceptor(new RequestConnControl()); httpproc.addInterceptor(new RequestUserAgent()); httpproc.addInterceptor(new RequestExpectContinue()); // We are going to use this object to synchronize between the // I/O event and main threads //CountDownLatch requestCount = new CountDownLatch(3); CountDownLatch requestCount = new CountDownLatch(1); BufferingHttpClientHandler handler = new MyBufferingHttpClientHandler(httpproc, new MyHttpRequestExecutionHandler(requestCount), new DefaultConnectionReuseStrategy(), params); handler.setEventListener(new EventLogger()); final IOEventDispatch ioEventDispatch = new DefaultClientIOEventDispatch(handler, params); Thread t = new Thread(new Runnable() { public void run() { try { ioReactor.execute(ioEventDispatch); } catch (InterruptedIOException ex) { System.err.println("Interrupted"); } catch (IOException e) { System.err.println("I/O error: " + e.getMessage()); }// w w w .j a va 2s .c o m System.out.println("Shutdown"); } }); t.start(); SessionRequest[] reqs = new SessionRequest[1]; reqs[0] = ioReactor.connect(new InetSocketAddress("ftp.osuosl.org", 80), null, new HttpHost("ftp.osuosl.org"), new MySessionRequestCallback(requestCount)); // Block until all connections signal // completion of the request execution requestCount.await(); System.out.println("Shutting down I/O reactor"); ioReactor.shutdown(); System.out.println("Done"); }
From source file:wh.contrib.RewardOptimizerHttpClient.java
public static void main(String[] args) throws Exception { HttpParams params = new BasicHttpParams(); params.setIntParameter(CoreConnectionPNames.SO_TIMEOUT, 30000) .setIntParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, 10000) .setIntParameter(CoreConnectionPNames.SOCKET_BUFFER_SIZE, 64 * 1024) .setBooleanParameter(CoreConnectionPNames.STALE_CONNECTION_CHECK, false) .setBooleanParameter(CoreConnectionPNames.TCP_NODELAY, true) .setParameter(CoreProtocolPNames.USER_AGENT, "HttpComponents/1.1 (RewardOptimizer - karlthepagan@gmail.com)"); final ConnectingIOReactor ioReactor = new DefaultConnectingIOReactor(2, params); BasicHttpProcessor httpproc = new BasicHttpProcessor(); httpproc.addInterceptor(new RequestContent()); httpproc.addInterceptor(new RequestTargetHost()); httpproc.addInterceptor(new RequestConnControl()); httpproc.addInterceptor(new RequestUserAgent()); httpproc.addInterceptor(new RequestExpectContinue()); // We are going to use this object to synchronize between the // I/O event and main threads RequestCount requestCount = new RequestCount(1); BufferingHttpClientHandler handler = new BufferingHttpClientHandler(httpproc, new MyHttpRequestExecutionHandler(requestCount), new DefaultConnectionReuseStrategy(), params); handler.setEventListener(new EventLogger()); final IOEventDispatch ioEventDispatch = new DefaultClientIOEventDispatch(handler, params); Thread t = new Thread(new Runnable() { public void run() { try { ioReactor.execute(ioEventDispatch); } catch (InterruptedIOException ex) { System.err.println("Interrupted"); } catch (IOException e) { System.err.println("I/O error: " + e.getMessage()); }//from w ww . j a va 2 s . c o m System.out.println("Shutdown"); } }); t.start(); List<SessionRequest> reqs = new ArrayList<SessionRequest>(); // reqs.add(ioReactor.connect( // new InetSocketAddress("www.yahoo.com", 80), // null, // new HttpHost("www.yahoo.com"), // null)); // reqs.add(ioReactor.connect( // new InetSocketAddress("www.google.com", 80), // null, // new HttpHost("www.google.ch"), // null)); // reqs.add(ioReactor.connect( // new InetSocketAddress("www.apache.org", 80), // null, // new HttpHost("www.apache.org"), // null)); reqs.add(ioReactor.connect(new InetSocketAddress("www.wowhead.com", 80), null, new HttpHost("www.wowhead.com"), null)); // Block until all connections signal // completion of the request execution synchronized (requestCount) { while (requestCount.getValue() > 0) { requestCount.wait(); } } System.out.println("Shutting down I/O reactor"); ioReactor.shutdown(); System.out.println("Done"); }
From source file:io.seldon.importer.articles.ItemAttributesImporter.java
/** * @param args//from www .j a v a 2 s . c om * @throws InterruptedException * @throws FileNotFoundException */ public static void main(String[] args) throws InterruptedException, FileNotFoundException { FailFast failFast = new FailFast(Thread.currentThread()); { // Fail Fast thread Thread fail_fast_thread = new Thread(failFast); fail_fast_thread.setName("fail_fast_thread"); fail_fast_thread.start(); } try { Args.parse(ItemAttributesImporter.class, args); { // Determine opMode by checking for urlFile if (urlFile != null) { opMode = OperationMode.OPERATION_MODE_FILE_IMPORTER; } } DefaultApiClient client = new DefaultApiClient(apiUrl, consumerKey, consumerSecret, API_TIMEOUT); ItemAttributesImporter fixer = new ItemAttributesImporter(client); fixer.setFailFast(failFast); fixer.run(); } catch (IllegalArgumentException e) { e.printStackTrace(); Args.usage(ItemAttributesImporter.class); } }
From source file:Snippet7.java
public static void main(String[] args) { final Display display = new Display(); final Image image = new Image(display, 16, 16); GC gc = new GC(image); gc.setBackground(display.getSystemColor(SWT.COLOR_RED)); gc.fillRectangle(image.getBounds()); gc.dispose();/*from www . j a v a 2 s . c om*/ final Shell shell = new Shell(display); shell.setText("Lazy Table"); shell.setLayout(new FillLayout()); final Table table = new Table(shell, SWT.BORDER | SWT.MULTI); table.setSize(200, 200); Thread thread = new Thread() { public void run() { for (int i = 0; i < 20000; i++) { if (table.isDisposed()) return; final int[] index = new int[] { i }; display.syncExec(new Runnable() { public void run() { if (table.isDisposed()) return; TableItem item = new TableItem(table, SWT.NONE); item.setText("Table Item " + index[0]); item.setImage(image); } }); } } }; thread.start(); shell.setSize(200, 200); shell.open(); while (!shell.isDisposed()) { if (!display.readAndDispatch()) display.sleep(); } image.dispose(); display.dispose(); }