List of usage examples for java.util Collections synchronizedList
public static <T> List<T> synchronizedList(List<T> list)
From source file:Synchronization.java
public static void main(String[] args) { Collection c = Collections.synchronizedCollection(new ArrayList()); List list = Collections.synchronizedList(new ArrayList()); Set s = Collections.synchronizedSet(new HashSet()); Map m = Collections.synchronizedMap(new HashMap()); }
From source file:PrepareProduction.java
public static void main(String[] args) throws Exception { List q = Collections.synchronizedList(new LinkedList<String>()); Thread p1 = new Thread(new PrepareProduction(q)); Thread c1 = new Thread(new DoProduction(q)); p1.start();/*from www . j av a2 s.c o m*/ c1.start(); p1.join(); c1.join(); }
From source file:Main.java
public static void main(String[] args) { Integer[] intArray = { 1, 2, 3, 4, 5, 6, 7, 8 }; List<Integer> listOfIntegers = new ArrayList<>(Arrays.asList(intArray)); List<Integer> serialStorage = new ArrayList<>(); System.out.println("Serial stream:"); listOfIntegers.stream()/*w w w . java2 s . c om*/ // Don't do this! It uses a stateful lambda expression. .map(e -> { serialStorage.add(e); return e; }) .forEachOrdered(e -> System.out.print(e + " ")); System.out.println(""); serialStorage.stream().forEachOrdered(e -> System.out.print(e + " ")); System.out.println(""); System.out.println("Parallel stream:"); List<Integer> parallelStorage = Collections.synchronizedList(new ArrayList<>()); listOfIntegers.parallelStream() // Don't do this! It uses a stateful lambda expression. .map(e -> { parallelStorage.add(e); return e; }) .forEachOrdered(e -> System.out.print(e + " ")); System.out.println(""); parallelStorage.stream().forEachOrdered(e -> System.out.print(e + " ")); System.out.println(""); }
From source file:AdderTask.java
public static void main(String[] args) { final int PHASE_COUNT = 2; Phaser phaser = new Phaser() { public boolean onAdvance(int phase, int parties) { System.out.println(//from w w w.j a v a2s . c o m "Phase:" + phase + ", Parties:" + parties + ", Arrived:" + this.getArrivedParties()); boolean terminatePhaser = false; if (phase >= PHASE_COUNT - 1 || parties == 0) { terminatePhaser = true; } return terminatePhaser; } }; List<Integer> list = Collections.synchronizedList(new ArrayList<Integer>()); int ADDER_COUNT = 3; phaser.bulkRegister(ADDER_COUNT + 1); for (int i = 1; i <= ADDER_COUNT; i++) { String taskName = "Task #" + i; AdderTask task = new AdderTask(taskName, phaser, list); task.start(); } while (!phaser.isTerminated()) { phaser.arriveAndAwaitAdvance(); } int sum = 0; for (Integer num : list) { sum = sum + num; } System.out.println("Sum = " + sum); }
From source file:org.soaplab.clients.BatchTestClient.java
/************************************************************************* * * Entry point...//from w w w. j av a 2 s . co m * *************************************************************************/ public static void main(String[] args) { try { BaseCmdLine cmd = getCmdLine(args, BatchTestClient.class); // service location and protocol parameters ServiceLocator mainLocator = InputUtils.getServiceLocator(cmd); // file(s) with the testing data (a list of tested // services and their inputs) String[] batchFiles = null; String batchFile = cmd.getParam("-batchfile"); if (batchFile != null) { // take it from the command-line batchFiles = new String[] { batchFile }; } else { // take it from the client configuration file batchFiles = ClientConfig.get().getStringArray(ClientConfig.PROP_BATCH_TEST_FILE); } if (batchFiles == null || batchFiles.length == 0) { log.error("A file with a list of service to test must be given. " + "Use '-batchfile' or a property '" + ClientConfig.PROP_BATCH_TEST_FILE + "'."); System.exit(1); } // other arguments boolean tableReport = (cmd.hasOption("-table") || ClientConfig.isEnabled(ClientConfig.PROP_BATCH_REPORT_TABLE, false)); boolean keepResults = (cmd.hasOption("-keep") || ClientConfig.isEnabled(ClientConfig.PROP_BATCH_KEEP_RESULTS, false)); int maxThreads = -1; String strMaxThreads = cmd.getParam("-maxthreads"); if (strMaxThreads == null) maxThreads = ClientConfig.getInt(ClientConfig.PROP_BATCH_MAX_THREADS, 25); else maxThreads = getInt(strMaxThreads); if (maxThreads < 0) maxThreads = 0; boolean oneByOne = (maxThreads == 1); // get a list of available services // (for validation purposes later) Set<String> services = new HashSet<String>(); for (String name : new SoaplabBaseClient(mainLocator).getAvailableAnalyses()) { services.add(name); } // loop and do it... List<Properties> reports = Collections.synchronizedList(new ArrayList<Properties>()); List<Thread> threads = Collections.synchronizedList(new ArrayList<Thread>()); int countNotAvailable = 0; title("Progress"); for (String file : batchFiles) { log.info("Using batch file " + file); // treat each batch file as a property configuration // file - together with a usual Soaplab Client // configuration file; this allows handling // substitutions of referenced properties, etc. CompositeConfiguration cfg = new CompositeConfiguration(); cfg.addConfiguration(ClientConfig.get()); cfg.addConfiguration(Config.get()); try { cfg.addConfiguration(new PropertiesConfiguration(file)); } catch (ConfigurationException e) { log.error("Loading batch file from '" + file + "' failed: " + e.getMessage()); continue; } // for (Iterator it = cfg.getKeys(); it.hasNext();) { String propertyName = (String) it.next(); if (!propertyName.startsWith(PREFIX_SERVICE_TO_TEST)) continue; String serviceName = StringUtils.removeStart(propertyName, PREFIX_SERVICE_TO_TEST); if (!services.contains(serviceName)) { // log.warn (serviceName + " is not available for testing"); countNotAvailable += 1; continue; } String[] inputs = cfg.getStringArray(propertyName); for (String input : inputs) { MyLocator locator = new MyLocator(serviceName, mainLocator); locator.enableKeepResults(keepResults); locator.setInputLine(input); if (oneByOne) { // sequential invocation qmsg(String.format("%-50s", "Running " + serviceName + "... ")); Properties report = callService(locator, reports); qmsgln("finished: " + report.getProperty(REPORT_JOB_STATUS)); } else { // do it in parallel startService(threads, locator, reports); if (maxThreads > 0) { // limit the number of threads // (just wait for some to finish) while (threads.size() >= maxThreads) { try { Thread.sleep(1000); } catch (Exception e) { } } } } } } } if (!oneByOne) { // wait for all the threads to finish while (threads.size() > 0) { try { Thread.sleep(1000); } catch (Exception e) { } } } msgln(""); // report all tests if (tableReport) createTableReport(reports); // report results int countSuccessful = 0; int countErrors = 0; for (Properties report : reports) { if (report.containsKey(REPORT_ERROR_MESSAGE)) { report.remove(REPORT_STACK_TRACE); countErrors += 1; createErrorReport(report); } else { String status = report.getProperty(REPORT_JOB_STATUS); if (SoaplabConstants.JOB_COMPLETED.equals(status)) { countSuccessful += 1; } else { countErrors += 1; createErrorReport(report); } } } // make a summary title("Summary"); msgln("Successfully: " + countSuccessful); msgln("Erroneously: " + countErrors); msgln("Not available: " + countNotAvailable); exit(0); } catch (Throwable e) { processErrorAndExit(e); } }
From source file:acmi.l2.clientmod.l2_version_switcher.Main.java
public static void main(String[] args) { if (args.length != 3 && args.length != 4) { System.out.println("USAGE: l2_version_switcher.jar host game version <--splash> <filter>"); System.out.println("EXAMPLE: l2_version_switcher.jar " + L2.NCWEST_HOST + " " + L2.NCWEST_GAME + " 1 \"system\\*\""); System.out.println(/*from w w w . ja v a 2 s. c o m*/ " l2_version_switcher.jar " + L2.PLAYNC_TEST_HOST + " " + L2.PLAYNC_TEST_GAME + " 48"); System.exit(0); } List<String> argsList = new ArrayList<>(Arrays.asList(args)); String host = argsList.get(0); String game = argsList.get(1); int version = Integer.parseInt(argsList.get(2)); Helper helper = new Helper(host, game, version); boolean available = false; try { available = helper.isAvailable(); } catch (IOException e) { System.err.print(e.getClass().getSimpleName()); if (e.getMessage() != null) { System.err.print(": " + e.getMessage()); } System.err.println(); } System.out.println(String.format("Version %d available: %b", version, available)); if (!available) { System.exit(0); } List<FileInfo> fileInfoList = null; try { fileInfoList = helper.getFileInfoList(); } catch (IOException e) { System.err.println("Couldn\'t get file info map"); System.exit(1); } boolean splash = argsList.remove("--splash"); if (splash) { Optional<FileInfo> splashObj = fileInfoList.stream() .filter(fi -> fi.getPath().contains("sp_32b_01.bmp")).findAny(); if (splashObj.isPresent()) { try (InputStream is = new FilterInputStream( Util.getUnzipStream(helper.getDownloadStream(splashObj.get().getPath()))) { @Override public int read() throws IOException { int b = super.read(); if (b >= 0) b ^= 0x36; return b; } @Override public int read(byte[] b, int off, int len) throws IOException { int r = super.read(b, off, len); if (r >= 0) { for (int i = 0; i < r; i++) b[off + i] ^= 0x36; } return r; } }) { new DataInputStream(is).readFully(new byte[28]); BufferedImage bi = ImageIO.read(is); JFrame frame = new JFrame("Lineage 2 [" + version + "] " + splashObj.get().getPath()); frame.setContentPane(new JComponent() { { setPreferredSize(new Dimension(bi.getWidth(), bi.getHeight())); } @Override protected void paintComponent(Graphics g) { g.drawImage(bi, 0, 0, null); } }); frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE); frame.pack(); frame.setLocationRelativeTo(null); frame.setVisible(true); } catch (IOException e) { e.printStackTrace(); } } else { System.out.println("Splash not found"); } return; } String filter = argsList.size() > 3 ? separatorsToSystem(argsList.get(3)) : null; File l2Folder = new File(System.getProperty("user.dir")); List<FileInfo> toUpdate = fileInfoList.parallelStream().filter(fi -> { String filePath = separatorsToSystem(fi.getPath()); if (filter != null && !wildcardMatch(filePath, filter, IOCase.INSENSITIVE)) return false; File file = new File(l2Folder, filePath); try { if (file.exists() && file.length() == fi.getSize() && Util.hashEquals(file, fi.getHash())) { System.out.println(filePath + ": OK"); return false; } } catch (IOException e) { System.out.println(filePath + ": couldn't check hash: " + e); return true; } System.out.println(filePath + ": need update"); return true; }).collect(Collectors.toList()); List<String> errors = Collections.synchronizedList(new ArrayList<>()); ExecutorService executor = Executors.newFixedThreadPool(16); CompletableFuture[] tasks = toUpdate.stream().map(fi -> CompletableFuture.runAsync(() -> { String filePath = separatorsToSystem(fi.getPath()); File file = new File(l2Folder, filePath); File folder = file.getParentFile(); if (!folder.exists()) { if (!folder.mkdirs()) { errors.add(filePath + ": couldn't create parent dir"); return; } } try (InputStream input = Util .getUnzipStream(new BufferedInputStream(helper.getDownloadStream(fi.getPath()))); OutputStream output = new BufferedOutputStream(new FileOutputStream(file))) { byte[] buffer = new byte[Math.min(fi.getSize(), 1 << 24)]; int pos = 0; int r; while ((r = input.read(buffer, pos, buffer.length - pos)) >= 0) { pos += r; if (pos == buffer.length) { output.write(buffer, 0, pos); pos = 0; } } if (pos != 0) { output.write(buffer, 0, pos); } System.out.println(filePath + ": OK"); } catch (IOException e) { String msg = filePath + ": FAIL: " + e.getClass().getSimpleName(); if (e.getMessage() != null) { msg += ": " + e.getMessage(); } errors.add(msg); } }, executor)).toArray(CompletableFuture[]::new); CompletableFuture.allOf(tasks).thenRun(() -> { for (String err : errors) System.err.println(err); executor.shutdown(); }); }
From source file:diffhunter.DiffHunter.java
/** * @param args the command line arguments * @throws org.apache.commons.cli.ParseException * @throws java.io.IOException//from w w w .jav a2s . c om */ public static void main(String[] args) throws ParseException, IOException { //String test_ = Paths.get("J:\\VishalData\\additional\\", "Sasan" + "_BDB").toAbsolutePath().toString(); // TODO code application logic here /*args = new String[] { "-i", "-b", "J:\\VishalData\\additional\\Ptbp2_E18_5_cortex_CLIP_mm9_plus_strand_sorted.bed", "-r", "J:\\VishalData\\additional\\mouse_mm9.txt", "-o", "J:\\VishalData" };*/ /*args = new String[] { "-c", "-r", "J:\\VishalData\\additional\\mouse_mm9.txt", "-1", "J:\\VishalData\\Ptbp2_Adult_testis_CLIP_mm9_plus_strand_sorted_BDB", "-2", "J:\\VishalData\\Ptbp2_E18_5_cortex_CLIP_mm9_plus_strand_sorted_BDB", "-w", "200", "-s", "50", "-o", "J:\\VishalData" };*/ Options options = new Options(); // add t option options.addOption("i", "index", false, "Indexing BED files."); options.addOption("b", "bed", true, "bed file to be indexed"); options.addOption("o", "output", true, "Folder that the index/comparison file will be created."); options.addOption("r", "reference", true, "Reference annotation file to be used for indexing"); options.addOption("c", "compare", false, "Finding differences between two conditions"); options.addOption("1", "first", true, "First sample index location"); options.addOption("2", "second", true, "Second sample index location"); options.addOption("w", "window", true, "Length of window for identifying differences"); options.addOption("s", "sliding", true, "Length of sliding"); CommandLineParser parser = new BasicParser(); CommandLine cmd = parser.parse(options, args); boolean indexing = false; boolean comparing = false; //Indexing! if (cmd.hasOption("i")) { //if(cmd.hasOption("1")) //System.err.println("sasan"); //System.out.println("sasa"); indexing = true; } else if (cmd.hasOption("c")) { //System.err.println(""); comparing = true; } else { //System.err.println("Option is not deteced."); HelpFormatter formatter = new HelpFormatter(); formatter.printHelp("diffhunter", options); return; } //Indexing is selected // if (indexing == true) { //Since indexing is true. //User have to provide file for indexing. if (!(cmd.hasOption("o") || cmd.hasOption("r") || cmd.hasOption("b"))) { HelpFormatter formatter = new HelpFormatter(); formatter.printHelp("diffhunter", options); return; } String bedfile_ = cmd.getOptionValue("b"); String reference_file = cmd.getOptionValue("r"); String folder_loc = cmd.getOptionValue("o"); String sample_name = FilenameUtils.getBaseName(bedfile_); try (Database B2 = BerkeleyDB_Box.Get_BerkeleyDB( Paths.get(folder_loc, sample_name + "_BDB").toAbsolutePath().toString(), true, sample_name)) { Indexer indexing_ = new Indexer(reference_file); indexing_.Make_Index(B2, bedfile_, Paths.get(folder_loc, sample_name + "_BDB").toAbsolutePath().toString()); B2.close(); } } else if (comparing == true) { if (!(cmd.hasOption("o") || cmd.hasOption("w") || cmd.hasOption("s") || cmd.hasOption("1") || cmd.hasOption("2"))) { HelpFormatter formatter = new HelpFormatter(); formatter.printHelp("diffhunter", options); return; } String folder_loc = cmd.getOptionValue("o"); int window_ = Integer.parseInt(cmd.getOptionValue("w")); //int window_=600; int slide_ = Integer.parseInt(cmd.getOptionValue("s")); String first = cmd.getOptionValue("1").replace("_BDB", ""); String second = cmd.getOptionValue("2").replace("_BDB", ""); String reference_file = cmd.getOptionValue("r"); //String folder_loc=cmd.getOptionValue("o"); String sample_name_first = FilenameUtils.getBaseName(first); String sample_name_second = FilenameUtils.getBaseName(second); Database B1 = BerkeleyDB_Box.Get_BerkeleyDB(first + "_BDB", false, sample_name_first); Database B2 = BerkeleyDB_Box.Get_BerkeleyDB(second + "_BDB", false, sample_name_second); List<String> first_condition_genes = Files .lines(Paths.get(first + "_BDB", sample_name_first + ".txt").toAbsolutePath()) .collect(Collectors.toList()); List<String> second_condition_genes = Files .lines(Paths.get(second + "_BDB", sample_name_second + ".txt").toAbsolutePath()) .collect(Collectors.toList()); System.out.println("First and second condition are loaded!!! "); List<String> intersection_ = new ArrayList<>(first_condition_genes); intersection_.retainAll(second_condition_genes); BufferedWriter output = new BufferedWriter( new FileWriter(Paths.get(folder_loc, "differences_" + window_ + "_s" + slide_ + "_c" + ".txt") .toAbsolutePath().toString(), false)); List<Result_Window> final_results = Collections.synchronizedList(new ArrayList<>()); Worker_New worker_class = new Worker_New(); worker_class.Read_Reference(reference_file); while (!intersection_.isEmpty()) { List<String> selected_genes = new ArrayList<>(); //if (intersection_.size()<=10000){selected_genes.addAll(intersection_.subList(0, intersection_.size()));} //else selected_genes.addAll(intersection_.subList(0, 10000)); if (intersection_.size() <= intersection_.size()) { selected_genes.addAll(intersection_.subList(0, intersection_.size())); } else { selected_genes.addAll(intersection_.subList(0, intersection_.size())); } intersection_.removeAll(selected_genes); //System.out.println("Intersection count is:"+intersection_.size()); //final List<Result_Window> resultssss_=new ArrayList<>(); IntStream.range(0, selected_genes.size()).parallel().forEach(i -> { System.out.println(selected_genes.get(i) + "\tprocessing......"); String gene_of_interest = selected_genes.get(i);//"ENSG00000142657|PGD";//intersection_.get(6);////"ENSG00000163395|IGFN1";//"ENSG00000270066|SCARNA2"; int start = worker_class.dic_genes.get(gene_of_interest).start_loc; int end = worker_class.dic_genes.get(gene_of_interest).end_loc; Map<Integer, Integer> first_ = Collections.EMPTY_MAP; try { first_ = BerkeleyDB_Box.Get_Coord_Read(B1, gene_of_interest); } catch (IOException | ClassNotFoundException ex) { Logger.getLogger(DiffHunter.class.getName()).log(Level.SEVERE, null, ex); } Map<Integer, Integer> second_ = Collections.EMPTY_MAP; try { second_ = BerkeleyDB_Box.Get_Coord_Read(B2, gene_of_interest); } catch (IOException | ClassNotFoundException ex) { Logger.getLogger(DiffHunter.class.getName()).log(Level.SEVERE, null, ex); } List<Window> top_windows_first = worker_class.Get_Top_Windows(window_, first_, slide_); List<Window> top_windows_second = worker_class.Get_Top_Windows(window_, second_, slide_); //System.out.println("passed for window peak call for gene \t"+selected_genes.get(i)); // System.out.println("top_window_first_Count\t"+top_windows_first.size()); // System.out.println("top_window_second_Count\t"+top_windows_second.size()); if (top_windows_first.isEmpty() && top_windows_second.isEmpty()) { return; } List<Result_Window> res_temp = new Worker_New().Get_Significant_Windows(gene_of_interest, start, end, top_windows_first, top_windows_second, second_, first_, sample_name_first, sample_name_second, 0.01); if (!res_temp.isEmpty()) { final_results.addAll(res_temp);//final_results.addAll(worker_class.Get_Significant_Windows(gene_of_interest, start, end, top_windows_first, top_windows_second, second_, first_, first_condition, second_condition, 0.01)); } //System.out.println(selected_genes.get(i)+"\tprocessed."); }); /*selected_genes.parallelStream().forEach(i -> { });*/ List<Double> pvals = new ArrayList<>(); for (int i = 0; i < final_results.size(); i++) { pvals.add(final_results.get(i).p_value); } List<Double> qvals = MultipleTestCorrection.benjaminiHochberg(pvals); System.out.println("Writing to file..."); output.append("Gene_Symbol\tContributing_Sample\tStart\tEnd\tOddsRatio\tp_Value\tFDR"); output.newLine(); for (int i = 0; i < final_results.size(); i++) { Result_Window item = final_results.get(i); output.append(item.associated_gene_symbol + "\t" + item.contributing_windows + "\t" + item.start_loc + "\t" + item.end_loc + "\t" + item.oddsratio_ + "\t" + item.p_value + "\t" + qvals.get(i)); //+ "\t" + item.average_other_readcount_cotributing + "\t" + item.average_other_readcount_cotributing + "\t" + item.average_window_readcount_non + "\t" + item.average_other_readcount_non); output.newLine(); } /* for (Result_Window item : final_results) { output.append(item.associated_gene_symbol + "\t" + item.contributing_windows + "\t" + item.start_loc + "\t" + item.end_loc + "\t" + item.oddsratio_ + "\t" + item.p_value); //+ "\t" + item.average_other_readcount_cotributing + "\t" + item.average_other_readcount_cotributing + "\t" + item.average_window_readcount_non + "\t" + item.average_other_readcount_non); output.newLine(); } */ final_results.clear(); } output.close(); } System.out.println("Done."); }
From source file:Main.java
private static void runTest() throws InterruptedException { Collection<String> syncList = Collections.synchronizedList(new ArrayList<String>(1)); List<String> list = Arrays.asList("A", "B", "C", "D"); List<Thread> threads = new ArrayList<Thread>(); for (final String s : list) { Thread thread = new Thread(new Runnable() { @Override/*www.j a v a2 s .c o m*/ public void run() { syncList.add(s); } }); threads.add(thread); thread.start(); } for (Thread thread : threads) { thread.join(); } System.out.println(syncList); }
From source file:Main.java
final static public List<Object> synchronizedList(final int size) { return Collections.synchronizedList(createList(size)); }
From source file:Main.java
/** * Constructs a new synchronized {@code List} based on a {@link LinkedList}. * /* w w w. j a v a 2 s .c o m*/ * @return a synchronized List */ public static <E> List<E> synchronizedList() { return Collections.synchronizedList(new LinkedList<E>()); }