List of usage examples for java.util Vector isEmpty
public synchronized boolean isEmpty()
From source file:Main.java
public static void main(String[] args) { Vector vec = new Vector(4); System.out.println("The vector is empty: " + vec.isEmpty()); vec.add(4);/*from w w w .j av a 2 s . c om*/ System.out.println("The vector is empty: " + vec.isEmpty()); }
From source file:Main.java
public static void main(String args[]) { Vector v = new Vector(5); for (int i = 0; i < 10; i++) { v.add(0, i);/*from w w w. java 2 s . c om*/ } System.out.println(v); v.setSize(0); System.out.println(v); System.out.println(v.isEmpty()); }
From source file:org.objectweb.proactive.examples.masterworker.nqueens.NQueensExample.java
@SuppressWarnings("unchecked") public static void main(String[] args) throws Exception { // Getting command line parameters and creating the master (see AbstractExample) init(args);//from w w w . j a v a 2s . c om if (master_vn_name == null) { master = new ProActiveMaster<QueryExtern, Pair<Long, Long>>(); } else { master = new ProActiveMaster<QueryExtern, Pair<Long, Long>>(descriptor_url, master_vn_name); } // handling termination even if something fails registerShutdownHook(new Runnable() { public void run() { master.terminate(true); } }); // NQueens tasks are small, therefore, workers should have a big pool of tasks to solve master.setInitialTaskFlooding(20); // Adding ressources if (schedulerURL != null) { master.addResources(schedulerURL, login, password, classpath); } else if (vn_name == null) { master.addResources(descriptor_url); } else { master.addResources(descriptor_url, vn_name); } System.out.println("Launching NQUEENS solutions finder for n = " + nqueen_board_size + " with a depth of " + nqueen_algorithm_depth); long sumResults = 0; long sumTime = 0; long begin = System.currentTimeMillis(); // Generating the queries for the NQueens Vector<Query> unresolvedqueries = QueryGenerator.generateQueries(nqueen_board_size, nqueen_algorithm_depth); // Splitting Queries Vector<QueryExtern> toSolve = new Vector<QueryExtern>(); while (!unresolvedqueries.isEmpty()) { Query query = unresolvedqueries.remove(0); Vector<Query> splitted = QueryGenerator.splitAQuery(query); if (!splitted.isEmpty()) { for (Query splitquery : splitted) { toSolve.add(new QueryExtern(splitquery)); } } else { toSolve.add(new QueryExtern(query)); } } master.solve(toSolve); // Print results on the fly while (!master.isEmpty()) { try { Pair<Long, Long> res = master.waitOneResult(); sumResults += res.getFirst(); sumTime += res.getSecond(); System.out.println("Current nb of results : " + sumResults); } catch (TaskException e) { // Exception in the algorithm e.printStackTrace(); } } // Calculation finished, printing summary and total number of solutions long end = System.currentTimeMillis(); int nbworkers = master.workerpoolSize(); System.out.println("Total number of configurations found for n = " + nqueen_board_size + " and with " + nbworkers + " workers : " + sumResults); System.out.println("Time needed with " + nbworkers + " workers : " + ((end - begin) / 3600000) + String.format("h %1$tMm %1$tSs %1$tLms", end - begin)); System.out.println("Total workers calculation time : " + (sumTime / 3600000) + String.format("h %1$tMm %1$tSs %1$tLms", sumTime)); PALifeCycle.exitSuccess(); }
From source file:com.turn.ttorrent.cli.TorrentMain.java
/** * Torrent reader and creator./*from w ww.j a v a 2 s . com*/ * * <p> * You can use the {@code main()} function of this class to read or create * torrent files. See usage for details. * </p> * */ public static void main(String[] args) { BasicConfigurator.configure(new ConsoleAppender(new PatternLayout("%-5p: %m%n"))); CmdLineParser parser = new CmdLineParser(); CmdLineParser.Option help = parser.addBooleanOption('h', "help"); CmdLineParser.Option filename = parser.addStringOption('t', "torrent"); CmdLineParser.Option create = parser.addBooleanOption('c', "create"); CmdLineParser.Option pieceLength = parser.addIntegerOption('l', "length"); CmdLineParser.Option announce = parser.addStringOption('a', "announce"); try { parser.parse(args); } catch (CmdLineParser.OptionException oe) { System.err.println(oe.getMessage()); usage(System.err); System.exit(1); } // Display help and exit if requested if (Boolean.TRUE.equals((Boolean) parser.getOptionValue(help))) { usage(System.out); System.exit(0); } String filenameValue = (String) parser.getOptionValue(filename); if (filenameValue == null) { usage(System.err, "Torrent file must be provided!"); System.exit(1); } Integer pieceLengthVal = (Integer) parser.getOptionValue(pieceLength); if (pieceLengthVal == null) { pieceLengthVal = Torrent.DEFAULT_PIECE_LENGTH; } else { pieceLengthVal = pieceLengthVal * 1024; } logger.info("Using piece length of {} bytes.", pieceLengthVal); Boolean createFlag = (Boolean) parser.getOptionValue(create); //For repeated announce urls @SuppressWarnings("unchecked") Vector<String> announceURLs = (Vector<String>) parser.getOptionValues(announce); String[] otherArgs = parser.getRemainingArgs(); if (Boolean.TRUE.equals(createFlag) && (otherArgs.length != 1 || announceURLs.isEmpty())) { usage(System.err, "Announce URL and a file or directory must be " + "provided to create a torrent file!"); System.exit(1); } OutputStream fos = null; try { if (Boolean.TRUE.equals(createFlag)) { if (filenameValue != null) { fos = new FileOutputStream(filenameValue); } else { fos = System.out; } //Process the announce URLs into URIs List<URI> announceURIs = new ArrayList<URI>(); for (String url : announceURLs) { announceURIs.add(new URI(url)); } //Create the announce-list as a list of lists of URIs //Assume all the URI's are first tier trackers List<List<URI>> announceList = new ArrayList<List<URI>>(); announceList.add(announceURIs); File source = new File(otherArgs[0]); if (!source.exists() || !source.canRead()) { throw new IllegalArgumentException( "Cannot access source file or directory " + source.getName()); } String creator = String.format("%s (ttorrent)", System.getProperty("user.name")); Torrent torrent = null; if (source.isDirectory()) { List<File> files = new ArrayList<File>( FileUtils.listFiles(source, TrueFileFilter.TRUE, TrueFileFilter.TRUE)); Collections.sort(files); torrent = Torrent.create(source, files, pieceLengthVal, announceList, creator); } else { torrent = Torrent.create(source, pieceLengthVal, announceList, creator); } torrent.save(fos); } else { Torrent.load(new File(filenameValue), true); } } catch (Exception e) { logger.error("{}", e.getMessage(), e); System.exit(2); } finally { if (fos != System.out) { IOUtils.closeQuietly(fos); } } }
From source file:com.p2p.peercds.cli.TorrentMain.java
/** * Torrent reader and creator.//from www .j a v a2 s. c o m * * <p> * You can use the {@code main()} function of this class to read or create * torrent files. See usage for details. * </p> * */ public static void main(String[] args) { BasicConfigurator.configure(new ConsoleAppender(new PatternLayout("%-5p: %m%n"))); CmdLineParser parser = new CmdLineParser(); CmdLineParser.Option help = parser.addBooleanOption('h', "help"); CmdLineParser.Option filename = parser.addStringOption('t', "torrent"); CmdLineParser.Option create = parser.addBooleanOption('c', "create"); CmdLineParser.Option announce = parser.addStringOption('a', "announce"); try { parser.parse(args); } catch (CmdLineParser.OptionException oe) { System.err.println(oe.getMessage()); usage(System.err); System.exit(1); } // Display help and exit if requested if (Boolean.TRUE.equals((Boolean) parser.getOptionValue(help))) { usage(System.out); System.exit(0); } String filenameValue = (String) parser.getOptionValue(filename); if (filenameValue == null) { usage(System.err, "Torrent file must be provided!"); System.exit(1); } Boolean createFlag = (Boolean) parser.getOptionValue(create); //For repeated announce urls @SuppressWarnings("unchecked") Vector<String> announceURLs = (Vector<String>) parser.getOptionValues(announce); String[] otherArgs = parser.getRemainingArgs(); if (Boolean.TRUE.equals(createFlag) && (otherArgs.length != 1 || announceURLs.isEmpty())) { usage(System.err, "Announce URL and a file or directory must be " + "provided to create a torrent file!"); System.exit(1); } OutputStream fos = null; try { if (Boolean.TRUE.equals(createFlag)) { if (filenameValue != null) { fos = new FileOutputStream(filenameValue); } else { fos = System.out; } //Process the announce URLs into URIs List<URI> announceURIs = new ArrayList<URI>(); for (String url : announceURLs) { announceURIs.add(new URI(url)); } //Create the announce-list as a list of lists of URIs //Assume all the URI's are first tier trackers List<List<URI>> announceList = new ArrayList<List<URI>>(); announceList.add(announceURIs); File source = new File(otherArgs[0]); if (!source.exists() || !source.canRead()) { throw new IllegalArgumentException( "Cannot access source file or directory " + source.getName()); } String creator = String.format("%s (ttorrent)", System.getProperty("user.name")); Torrent torrent = null; if (source.isDirectory()) { File[] files = source.listFiles(Constants.hiddenFilesFilter); Arrays.sort(files); torrent = Torrent.create(source, Arrays.asList(files), announceList, creator); } else { torrent = Torrent.create(source, announceList, creator); } torrent.save(fos); } else { Torrent.load(new File(filenameValue), true); } } catch (Exception e) { logger.error("{}", e.getMessage(), e); System.exit(2); } finally { if (fos != System.out) { IOUtils.closeQuietly(fos); } } }
From source file:routercc8.DistanceVector.java
public static void main(String args[]) { DistanceVector d = new DistanceVector("B", ".\\src\\routercc8\\conf.ini"); Vector newmin = new Vector(); System.out.println("Start:" + d.mins.toString()); System.out.println(d.dv.toString()); d.recibeMinimo("A", "B", 3); d.recibeMinimo("A", "C", 23); newmin = d.calcular();/*from w ww.j av a 2 s .c om*/ if (!newmin.isEmpty()) { System.out.println("1nuevos Minimos: " + newmin.toString()); } System.out.println(d.mins.toString()); System.out.println(d.dv.toString()); d.recibeMinimo("C", "D", 5); d.recibeMinimo("C", "B", 2); d.recibeMinimo("C", "A", 23); newmin = d.calcular(); if (!newmin.isEmpty()) { System.out.println("2nuevos Minimos: " + newmin.toString()); } System.out.println(d.mins.toString()); System.out.println(d.dv.toString()); d.recibeMinimo("D", "C", 5); newmin = d.calcular(); if (!newmin.isEmpty()) { System.out.println("3nuevos Minimos: " + newmin.toString()); } System.out.println(d.mins.toString()); System.out.println(d.dv.toString()); System.out.println("T1"); System.out.println(); //T = 1; d.recibeMinimo("A", "C", 5); d.recibeMinimo("A", "D", 28); newmin = d.calcular(); if (!newmin.isEmpty()) { System.out.println("4nuevos Minimos: " + newmin.toString()); } System.out.println(d.mins.toString()); System.out.println(d.dv.toString()); d.recibeMinimo("C", "A", 5); newmin = d.calcular(); if (!newmin.isEmpty()) { System.out.println("5nuevos Minimos: " + newmin.toString()); } System.out.println(d.mins.toString()); System.out.println(d.dv.toString()); d.recibeMinimo("D", "A", 28); d.recibeMinimo("D", "B", 7); newmin = d.calcular(); if (!newmin.isEmpty()) { System.out.println("6nuevos Minimos: " + newmin.toString()); } System.out.println(d.mins.toString()); System.out.println(d.dv.toString()); //T=2 System.out.println("T2"); System.out.println(); d.recibeMinimo("D", "A", 10); newmin = d.calcular(); if (!newmin.isEmpty()) { System.out.println("7nuevos Minimos: " + newmin.toString()); } System.out.println(d.mins.toString()); System.out.println(d.dv.toString()); d.recibeMinimo("A", "D", 99); newmin = d.calcular(); if (!newmin.isEmpty()) { System.out.println("8nuevos Minimos: " + newmin.toString()); } System.out.println(d.mins.toString()); System.out.println(d.getMin("D")); System.out.println(d.dv.toString()); }
From source file:com.genentech.application.property.SDFCalculate.java
public static void main(String args[]) { String usage = "java SDFCalculate [options] <list of space separated properties>\n"; Options options = new Options(); // add options options.addOption("TPSA_P", false, "Count phosphorus atoms, default is false. (optional)"); options.addOption("TPSA_S", false, "Count sulfur atoms, default is false. (optional)"); options.addOption("cLogP", true, "SDtag where cLogP is stored, default is cLogP (optional)"); options.addOption("in", true, "inFile in OE formats: Ex: a.sdf or .sdf"); options.addOption("out", true, "outputfile in OE formats. Ex: a.sdf or .sdf "); try {/*from ww w . ja v a 2 s .c om*/ boolean countS = false; boolean countP = false; // append list of valid properties and their descriptions to the usage statement Iterator<Entry<String, String>> i = propsMap.entrySet().iterator(); while (i.hasNext()) { Map.Entry<String, String> me = i.next(); usage = usage + me.getKey() + ":\t" + me.getValue() + "\n"; } CommandLineParser parser = new PosixParser(); CommandLine cmd = parser.parse(options, args); if (cmd.hasOption("TPSA_P")) countP = true; if (cmd.hasOption("TPSA_S")) countS = true; // get list of properties Vector<String> propsList = new Vector<String>(Arrays.asList(cmd.getArgs())); if (propsList.isEmpty()) { HelpFormatter formatter = new HelpFormatter(); formatter.printHelp(usage, options); System.exit(1); } //make sure list of requested pros are valid props for (String p : propsList) { if (!propsMap.containsKey(p)) { System.err.println(p + " is not a valid property."); HelpFormatter formatter = new HelpFormatter(); formatter.printHelp(usage, options); System.exit(1); } } // get cLogP SD label tag option value String cLogPTag = "cLogP"; if (cmd.hasOption("cLogP")) { cLogPTag = cmd.getOptionValue("cLogP"); } String inFile = cmd.getOptionValue("in"); if (inFile == null) { HelpFormatter formatter = new HelpFormatter(); formatter.printHelp(usage, options); System.exit(1); } String outFile = cmd.getOptionValue("out"); if (outFile == null) { HelpFormatter formatter = new HelpFormatter(); formatter.printHelp(usage, options); System.exit(1); } String filename = "smarts.xml"; URL url = SDFCalculate.class.getResource(filename); Element root = XMLUtil.getRootElement(url, false); SDFCalculate test = new SDFCalculate(outFile, cLogPTag, countP, countS, root); test.calcProperties(inFile, propsList); } catch (ParseException e) { HelpFormatter formatter = new HelpFormatter(); formatter.printHelp(usage, options); System.exit(1); } catch (Exception e) { e.printStackTrace(); } }
From source file:org.apache.nutch.tools.DmozParser.java
/** * Command-line access. User may add URLs via a flat text file * or the structured DMOZ file. By default, we ignore Adult * material (as categorized by DMOZ).//from w w w . j a va2 s. c o m */ public static void main(String argv[]) throws Exception { if (argv.length < 1) { System.err.println( "Usage: DmozParser <dmoz_file> [-subset <subsetDenominator>] [-includeAdultMaterial] [-skew skew] [-topicFile <topic list file>] [-topic <topic> [-topic <topic> [...]]]"); return; } // // Parse the command line, figure out what kind of // URL file we need to load // int subsetDenom = 1; int skew = 0; String dmozFile = argv[0]; boolean includeAdult = false; Pattern topicPattern = null; Vector<String> topics = new Vector<String>(); Configuration conf = NutchConfiguration.create(); FileSystem fs = FileSystem.get(conf); try { for (int i = 1; i < argv.length; i++) { if ("-includeAdultMaterial".equals(argv[i])) { includeAdult = true; } else if ("-subset".equals(argv[i])) { subsetDenom = Integer.parseInt(argv[i + 1]); i++; } else if ("-topic".equals(argv[i])) { topics.addElement(argv[i + 1]); i++; } else if ("-topicFile".equals(argv[i])) { addTopicsFromFile(argv[i + 1], topics); i++; } else if ("-skew".equals(argv[i])) { skew = Integer.parseInt(argv[i + 1]); i++; } } DmozParser parser = new DmozParser(); if (!topics.isEmpty()) { String regExp = new String("^("); int j = 0; for (; j < topics.size() - 1; ++j) { regExp = regExp.concat(topics.get(j)); regExp = regExp.concat("|"); } regExp = regExp.concat(topics.get(j)); regExp = regExp.concat(").*"); LOG.info("Topic selection pattern = " + regExp); topicPattern = Pattern.compile(regExp); } parser.parseDmozFile(new File(dmozFile), subsetDenom, includeAdult, skew, topicPattern); } finally { fs.close(); } }
From source file:edu.umn.cs.spatialHadoop.operations.KNN.java
public static void main(String[] args) throws IOException { final OperationsParams params = new OperationsParams(new GenericOptionsParser(args)); Path[] paths = params.getPaths(); if (paths.length <= 1 && !params.checkInput()) { printUsage();/*from www . ja va 2 s.c om*/ System.exit(1); } if (paths.length > 1 && !params.checkInputOutput()) { printUsage(); System.exit(1); } final Path inputFile = params.getInputPath(); int count = params.getInt("count", 1); double closeness = params.getFloat("closeness", -1.0f); final Point[] queryPoints = closeness < 0 ? params.getShapes("point", new Point()) : new Point[count]; final FileSystem fs = inputFile.getFileSystem(params); final int k = params.getInt("k", 1); int concurrency = params.getInt("concurrency", 100); if (k == 0) { LOG.warn("k = 0"); } if (queryPoints.length == 0) { printUsage(); throw new RuntimeException("Illegal arguments"); } final Path outputPath = paths.length > 1 ? paths[1] : null; if (closeness >= 0) { // Get query points according to its closeness to grid intersections GlobalIndex<Partition> gindex = SpatialSite.getGlobalIndex(fs, inputFile); long seed = params.getLong("seed", System.currentTimeMillis()); Random random = new Random(seed); for (int i = 0; i < count; i++) { int i_block = random.nextInt(gindex.size()); int direction = random.nextInt(4); // Generate a point in the given direction // Get center point (x, y) Iterator<Partition> iterator = gindex.iterator(); while (i_block-- >= 0) iterator.next(); Partition partition = iterator.next(); double cx = (partition.x1 + partition.x2) / 2; double cy = (partition.y1 + partition.y2) / 2; double cw = partition.x2 - partition.x1; double ch = partition.y2 - partition.y1; int signx = ((direction & 1) == 0) ? 1 : -1; int signy = ((direction & 2) == 1) ? 1 : -1; double x = cx + cw * closeness / 2 * signx; double y = cy + ch * closeness / 2 * signy; queryPoints[i] = new Point(x, y); } } final BooleanWritable exceptionHappened = new BooleanWritable(); Thread.UncaughtExceptionHandler h = new Thread.UncaughtExceptionHandler() { public void uncaughtException(Thread th, Throwable ex) { ex.printStackTrace(); exceptionHappened.set(true); } }; // Run each query in a separate thread final Vector<Thread> threads = new Vector<Thread>(); for (int i = 0; i < queryPoints.length; i++) { Thread thread = new Thread() { @Override public void run() { try { Point query_point = queryPoints[threads.indexOf(this)]; OperationsParams newParams = new OperationsParams(params); OperationsParams.setShape(newParams, "point", query_point); Job job = knn(inputFile, outputPath, params); } catch (IOException e) { e.printStackTrace(); } catch (InterruptedException e) { e.printStackTrace(); } catch (ClassNotFoundException e) { e.printStackTrace(); } } }; thread.setUncaughtExceptionHandler(h); threads.add(thread); } long t1 = System.currentTimeMillis(); do { // Ensure that there is at least MaxConcurrentThreads running int i = 0; while (i < concurrency && i < threads.size()) { Thread.State state = threads.elementAt(i).getState(); if (state == Thread.State.TERMINATED) { // Thread already terminated, remove from the queue threads.remove(i); } else if (state == Thread.State.NEW) { // Start the thread and move to next one threads.elementAt(i++).start(); } else { // Thread is still running, skip over it i++; } } if (!threads.isEmpty()) { try { // Sleep for 10 seconds or until the first thread terminates threads.firstElement().join(10000); } catch (InterruptedException e) { e.printStackTrace(); } } } while (!threads.isEmpty()); long t2 = System.currentTimeMillis(); if (exceptionHappened.get()) throw new RuntimeException("Not all jobs finished correctly"); System.out.println("Time for " + queryPoints.length + " jobs is " + (t2 - t1) + " millis"); System.out.println("Total iterations: " + TotalIterations); }
From source file:edu.umn.cs.sthadoop.trajectory.KNNDTW.java
public static void main(String[] args) throws IOException { args = new String[10]; args[0] = "/export/scratch/mntgData/geolifeGPS/geolife_Trajectories_1.3/HDFS/index_geolife/yyyy-MM/2008-05"; args[1] = "/export/scratch/mntgData/geolifeGPS/geolife_Trajectories_1.3/HDFS/knn-dis-result"; args[2] = "shape:edu.umn.cs.sthadoop.trajectory.GeolifeTrajectory"; args[3] = "interval:2008-05-01,2008-05-30"; args[4] = "time:month"; args[5] = "k:1"; args[6] = "traj:39.9119983,116.606835;39.9119783,116.6065483;39.9119599,116.6062649;39.9119416,116.6059899;39.9119233,116.6057282;39.9118999,116.6054783;39.9118849,116.6052366;39.9118666,116.6050099;39.91185,116.604775;39.9118299,116.604525;39.9118049,116.6042649;39.91177,116.6040166;39.9117516,116.6037583;39.9117349,116.6035066;39.9117199,116.6032666;39.9117083,116.6030232;39.9117,116.6027566;39.91128,116.5969383;39.9112583,116.5966766;39.9112383,116.5964232;39.9112149,116.5961699;39.9111933,116.5959249;39.9111716,116.5956883"; args[7] = "-overwrite"; args[8] = "-local";// "-no-local"; args[9] = "point:39.9119983,116.606835"; final OperationsParams params = new OperationsParams(new GenericOptionsParser(args)); Path[] paths = params.getPaths(); if (paths.length <= 1 && !params.checkInput()) { printUsage();/*from w w w. j a v a2 s. co m*/ System.exit(1); } if (paths.length > 1 && !params.checkInputOutput()) { printUsage(); System.exit(1); } final Path inputFile = params.getInputPath(); int count = params.getInt("count", 1); double closeness = params.getFloat("closeness", -1.0f); final Point[] queryPoints = closeness < 0 ? params.getShapes("point", new Point()) : new Point[count]; final FileSystem fs = inputFile.getFileSystem(params); final int k = params.getInt("k", 1); int concurrency = params.getInt("concurrency", 100); if (k == 0) { LOG.warn("k = 0"); } if (queryPoints.length == 0) { printUsage(); throw new RuntimeException("Illegal arguments"); } final Path outputPath = paths.length > 1 ? paths[1] : null; if (closeness >= 0) { // Get query points according to its closeness to grid intersections GlobalIndex<Partition> gindex = SpatialSite.getGlobalIndex(fs, inputFile); long seed = params.getLong("seed", System.currentTimeMillis()); Random random = new Random(seed); for (int i = 0; i < count; i++) { int i_block = random.nextInt(gindex.size()); int direction = random.nextInt(4); // Generate a point in the given direction // Get center point (x, y) Iterator<Partition> iterator = gindex.iterator(); while (i_block-- >= 0) iterator.next(); Partition partition = iterator.next(); double cx = (partition.x1 + partition.x2) / 2; double cy = (partition.y1 + partition.y2) / 2; double cw = partition.x2 - partition.x1; double ch = partition.y2 - partition.y1; int signx = ((direction & 1) == 0) ? 1 : -1; int signy = ((direction & 2) == 1) ? 1 : -1; double x = cx + cw * closeness / 2 * signx; double y = cy + ch * closeness / 2 * signy; queryPoints[i] = new Point(x, y); } } final BooleanWritable exceptionHappened = new BooleanWritable(); Thread.UncaughtExceptionHandler h = new Thread.UncaughtExceptionHandler() { public void uncaughtException(Thread th, Throwable ex) { ex.printStackTrace(); exceptionHappened.set(true); } }; // Run each query in a separate thread final Vector<Thread> threads = new Vector<Thread>(); for (int i = 0; i < queryPoints.length; i++) { Thread thread = new Thread() { @Override public void run() { try { Point query_point = queryPoints[threads.indexOf(this)]; OperationsParams newParams = new OperationsParams(params); OperationsParams.setShape(newParams, "point", query_point); Job job = knn(inputFile, outputPath, params); } catch (IOException e) { e.printStackTrace(); } catch (InterruptedException e) { e.printStackTrace(); } catch (ClassNotFoundException e) { e.printStackTrace(); } } }; thread.setUncaughtExceptionHandler(h); threads.add(thread); } long t1 = System.currentTimeMillis(); do { // Ensure that there is at least MaxConcurrentThreads running int i = 0; while (i < concurrency && i < threads.size()) { Thread.State state = threads.elementAt(i).getState(); if (state == Thread.State.TERMINATED) { // Thread already terminated, remove from the queue threads.remove(i); } else if (state == Thread.State.NEW) { // Start the thread and move to next one threads.elementAt(i++).start(); } else { // Thread is still running, skip over it i++; } } if (!threads.isEmpty()) { try { // Sleep for 10 seconds or until the first thread terminates threads.firstElement().join(10000); } catch (InterruptedException e) { e.printStackTrace(); } } } while (!threads.isEmpty()); long t2 = System.currentTimeMillis(); if (exceptionHappened.get()) throw new RuntimeException("Not all jobs finished correctly"); System.out.println("Time for " + queryPoints.length + " jobs is " + (t2 - t1) + " millis"); System.out.println("Total iterations: " + TotalIterations); }