List of usage examples for java.util Collections synchronizedList
public static <T> List<T> synchronizedList(List<T> list)
From source file:com.cemso.action.DeviceAction.java
/** * Mutil thread push selected playlist//from ww w .j ava 2 s .c o m */ public String pushPlaylist1() { try { if (log.isDebugEnabled()) { log.debug("the selected playlist is: " + id); log.debug("the device's ip address is : " + ip); } boolean flag = false; if (ip.contains("_") && ip.length() > 15) { ip = ip.substring(1); String[] ips = ip.split("_"); List<String> ipList = Collections.synchronizedList(new ArrayList<String>()); for (int i = 0; i < ips.length; i++) { ipList.add(ips[i]); } PushPlaylistExecutor executor = new PushPlaylistExecutor(); executor.setPlaylistId(id); executor.setIps(ipList); while (executor.ips != null && !executor.ips.isEmpty()) { if (executor.bucketSize <= 5) { new Thread(executor.new Consumer()).start(); } } } else { if (ip.contains("_")) { ip = ip.replace("_", ""); } try { flag = deviceService.pushPlaylist(id, ip); } catch (Exception e) { if (log.isErrorEnabled()) { log.error(e.getMessage()); } e.printStackTrace(); flag = false; } } if (flag) { pushStatus = "true"; } else { pushStatus = "false"; } return "pushStatus"; } catch (Exception e) { if (log.isErrorEnabled()) { log.error(e.getMessage()); } e.printStackTrace(); return ERROR; } }
From source file:org.xmlsh.sh.shell.Shell.java
public List<ShellThread> getChildren(boolean create) { // mChildren is only set never chaqnged or cleared // Memory Barrier if (mChildren == null && create) { synchronized (this) { if (mChildren == null) mChildren = Collections.synchronizedList(new ArrayList<ShellThread>()); }/*from w w w .j a v a2s . c o m*/ } return mChildren; }
From source file:org.jdesktop.swingworker.AccumulativeRunnable.java
public final void testWorkFlow() throws Exception { final List<Object> goldenSequence = Arrays.asList(new Object[]{StateValue.STARTED, "done", StateValue.DONE}); final List<Object> sequence = Collections.synchronizedList(new ArrayList<Object>()); final Exchanger<List<Object>> listExchanger = new Exchanger<List<Object>>(); // w w w. j a va 2 s. c o m final SwingWorker<?,?> test = new SwingWorker<Object,Object>() { @Override protected Object doInBackground() throws Exception { return null; } @Override protected void done() { sequence.add("done"); } }; test.addPropertyChangeListener( new PropertyChangeListener() { public void propertyChange(PropertyChangeEvent evt) { if ("state".equals(evt.getPropertyName())) { sequence.add(evt.getNewValue()); if (StateValue.DONE == evt.getNewValue()) { try { listExchanger.exchange(sequence); } catch (Exception ignore) { ignore.printStackTrace(); } } } } }); test.execute(); assertEquals(goldenSequence, listExchanger.exchange(null, TIME_OUT, TIME_OUT_UNIT)); }
From source file:gdsc.smlm.ij.plugins.DriftCalculator.java
/** * Calculate the drift of images to the reference image. Update the current drift parameters. * /* ww w . j a va 2 s . c om*/ * @param imageT * The frame number for each image * @param scale * The image scale (used to adjust the drift to the correct size) * @param dx * The X drift * @param dy * The Y drift * @param originalDriftTimePoints * Non-zero when the frame number refers to an aligned image frame * @param smoothing * LOESS smoothing parameter * @param iterations * LOESS iterations parameter * @param images * The images to align * @param reference * The reference image * @param includeCurrentDrift * Set to true if the input images already have the current drift applied. The new drift will be added to * the current drift. * @return */ private double calculateDrift(int[] imageT, float scale, double[] dx, double[] dy, double[] originalDriftTimePoints, double smoothing, int iterations, final ImageProcessor[] images, FloatProcessor reference, boolean includeCurrentDrift) { // Align tracker.status("Aligning images"); final AlignImagesFFT aligner = new AlignImagesFFT(); aligner.init(reference, WindowMethod.NONE, false); final Rectangle alignBounds = AlignImagesFFT.createHalfMaxBounds(reference.getWidth(), reference.getHeight(), reference.getWidth(), reference.getHeight()); List<double[]> alignments = Collections.synchronizedList(new ArrayList<double[]>(images.length)); List<Future<?>> futures = new LinkedList<Future<?>>(); int imagesPerThread = getImagesPerThread(images); for (int i = 0; i < images.length; i += imagesPerThread) { futures.add(threadPool.submit( new ImageAligner(aligner, images, imageT, alignBounds, alignments, i, i + imagesPerThread))); } Utils.waitForCompletion(futures); tracker.progress(1); // Used to flag when an alignment has failed originalDriftTimePoints = Arrays.copyOf(originalDriftTimePoints, originalDriftTimePoints.length); double[] newDx = new double[dx.length]; double[] newDy = new double[dy.length]; int ok = 0; for (double[] result : alignments) { int t = (int) result[2]; if (Double.isNaN(result[0])) { // TODO: How to ignore bad alignments? // Only do smoothing where there was an alignment? originalDriftTimePoints[t] = 0; tracker.log("WARNING : Unable to align image for time %d to the overall projection", t); } else { ok++; newDx[t] = result[0] / scale; newDy[t] = result[1] / scale; if (includeCurrentDrift) { // New drift = update + previous drift newDx[t] += dx[t]; newDy[t] += dy[t]; } } } if (ok < 2) { tracker.log("ERROR : Unable to align more than 1 image to the overall projection"); return Double.NaN; } // Store the pure drift values for plotting calculatedTimepoints = Arrays.copyOf(originalDriftTimePoints, originalDriftTimePoints.length); lastdx = Arrays.copyOf(newDx, newDx.length); lastdy = Arrays.copyOf(newDy, newDy.length); // Perform smoothing if (smoothing > 0) { tracker.status("Smoothing drift"); if (!smooth(newDx, newDy, originalDriftTimePoints, smoothing, iterations)) return Double.NaN; } // Interpolate values for all time limits tracker.status("Interpolating drift"); interpolate(newDx, newDy, originalDriftTimePoints); // Average drift correction for the calculated points should be zero to allow change comparison normalise(newDx, originalDriftTimePoints); normalise(newDy, originalDriftTimePoints); // Calculate change and update the input drift parameters double change = 0; for (int t = 0; t < dx.length; t++) { if (originalDriftTimePoints[t] != 0) { double d1 = dx[t] - newDx[t]; double d2 = dy[t] - newDy[t]; change += Math.sqrt(d1 * d1 + d2 * d2); } // Update all points since interpolation has already been done dx[t] = newDx[t]; dy[t] = newDy[t]; } tracker.status(""); return change; }
From source file:com.android.yijiang.kzx.http.AsyncHttpClient.java
/** * Puts a new request in queue as a new thread in pool to be executed * * @param client HttpClient to be used for request, can differ in single requests * @param contentType MIME body type, for POST and PUT requests, may be null * @param context Context of Android application, to hold the reference of request * @param httpContext HttpContext in which the request will be executed * @param responseHandler ResponseHandler or its subclass to put the response into * @param uriRequest instance of HttpUriRequest, which means it must be of HttpDelete, * HttpPost, HttpGet, HttpPut, etc. * @return RequestHandle of future request process *//*from w w w .j a v a 2s. c o m*/ protected RequestHandle sendRequest(DefaultHttpClient client, HttpContext httpContext, HttpUriRequest uriRequest, String contentType, ResponseHandlerInterface responseHandler, Context context) { if (uriRequest == null) { throw new IllegalArgumentException("HttpUriRequest must not be null"); } if (responseHandler == null) { throw new IllegalArgumentException("ResponseHandler must not be null"); } if (responseHandler.getUseSynchronousMode()) { throw new IllegalArgumentException( "Synchronous ResponseHandler used in AsyncHttpClient. You should create your response handler in a looper thread or use SyncHttpClient instead."); } if (contentType != null) { uriRequest.setHeader(HEADER_CONTENT_TYPE, contentType); } responseHandler.setRequestHeaders(uriRequest.getAllHeaders()); responseHandler.setRequestURI(uriRequest.getURI()); AsyncHttpRequest request = newAsyncHttpRequest(client, httpContext, uriRequest, contentType, responseHandler, context); threadPool.submit(request); RequestHandle requestHandle = new RequestHandle(request); if (context != null) { // Add request to request map List<RequestHandle> requestList = requestMap.get(context); synchronized (requestMap) { if (requestList == null) { requestList = Collections.synchronizedList(new LinkedList<RequestHandle>()); requestMap.put(context, requestList); } } if (responseHandler instanceof RangeFileAsyncHttpResponseHandler) ((RangeFileAsyncHttpResponseHandler) responseHandler).updateRequestHeaders(uriRequest); requestList.add(requestHandle); Iterator<RequestHandle> iterator = requestList.iterator(); while (iterator.hasNext()) { if (iterator.next().shouldBeGarbageCollected()) { iterator.remove(); } } } return requestHandle; }
From source file:org.apache.hadoop.raid.RaidShell.java
/** * checks the raided file system, prints a list of corrupt files to * this.out and returns the number of corrupt files. * Also prints out the total number of files with at least one missing block. * When called with '-retNumStrpsMissingBlks', also prints out number of stripes * with certain number of blocks missing for files using the 'RS' codec. *///from w ww .ja v a 2 s.c om public void fsck(String cmd, String[] args, int startIndex) throws IOException { final int numFsckArgs = args.length - startIndex; int numThreads = 16; String path = "/"; boolean argsOk = false; boolean countOnly = false; boolean cntMissingBlksPerStrp = false; boolean listRecoverableFile = false; if (numFsckArgs >= 1) { argsOk = true; path = args[startIndex]; } for (int i = startIndex + 1; i < args.length; i++) { if (args[i].equals("-threads")) { numThreads = Integer.parseInt(args[++i]); } else if (args[i].equals("-count")) { countOnly = true; } else if (args[i].equals("-retNumStrpsMissingBlks")) { cntMissingBlksPerStrp = true; } else if (args[i].equals("-listrecoverablefiles")) { listRecoverableFile = true; } } if (!argsOk) { printUsage(cmd); return; } final String dateString = dateFormat.format(new Date()); ; System.err .println("Running RAID FSCK with " + numThreads + " threads on " + path + " at time " + dateString); FileSystem fs = (new Path(path)).getFileSystem(conf); // if we got a raid fs, get the underlying fs if (fs instanceof DistributedRaidFileSystem) { fs = ((DistributedRaidFileSystem) fs).getFileSystem(); } // check that we have a distributed fs if (!(fs instanceof DistributedFileSystem)) { throw new IOException("expected DistributedFileSystem but got " + fs.getClass().getName()); } final DistributedFileSystem dfs = (DistributedFileSystem) fs; // get a list of corrupted files (not considering parity blocks just yet) // from the name node // these are the only files we need to consider: // if a file has no corrupted data blocks, it is OK even if some // of its parity blocks are corrupted, so no further checking is // necessary System.err.println("Querying NameNode for list of corrupt files under " + path); final String[] files = DFSUtil.getCorruptFiles(dfs, path); final List<String> corruptFileCandidates = new LinkedList<String>(); for (final String f : files) { // if this file is a parity file // or if it does not start with the specified path, // ignore it boolean matched = false; for (Codec c : Codec.getCodecs()) { if (f.startsWith(c.getParityPrefix())) { matched = true; } } if (!matched) { corruptFileCandidates.add(f); } } // filter files marked for deletion RaidUtils.filterTrash(conf, corruptFileCandidates); //clear numStrpMissingBlks if missing blocks per stripe is to be counted if (cntMissingBlksPerStrp) { for (AtomicLongArray numStrpMissingBlks : numStrpMissingBlksMap.values()) { for (int i = 0; i < numStrpMissingBlks.length(); i++) { numStrpMissingBlks.set(i, 0); } } } System.err.println("Processing " + corruptFileCandidates.size() + " possibly corrupt files using " + numThreads + " threads"); ExecutorService executor = null; ThreadFactory factory = new ThreadFactory() { final AtomicInteger tnum = new AtomicInteger(); public Thread newThread(Runnable r) { Thread t = new Thread(r); t.setName("Raidfsck-" + dateString + "-" + tnum.incrementAndGet()); return t; } }; if (numThreads > 1) { executor = Executors.newFixedThreadPool(numThreads, factory); } else { numThreads = 1; } final List<String> unRecoverableFiles = Collections.synchronizedList(new LinkedList<String>()); final List<String> recoverableFiles = Collections.synchronizedList(new LinkedList<String>()); final boolean finalCountOnly = countOnly; final boolean finalMissingBlksPerStrpCnt = cntMissingBlksPerStrp; final boolean finalListRecoverableFile = listRecoverableFile; final int step = numThreads; final AtomicInteger finishNum = new AtomicInteger(0); for (int i = 0; i < numThreads; i++) { if (!dfs.getClient().isOpen()) { throw new IOException("Filesystem closed."); } final int startIdx = i; Runnable work = new Runnable() { public void run() { try { for (int idx = startIdx; idx < corruptFileCandidates.size(); idx += step) { String corruptFileCandidate = corruptFileCandidates.get(idx); boolean corrupt = false; try { FileStatus corruptStat; try { corruptStat = dfs.getFileStatus(new Path(corruptFileCandidate)); } catch (FileNotFoundException fnfe) { continue; } if (!dfs.getClient().isOpen()) { LOG.warn("Filesystem closed."); return; } corrupt = isFileCorrupt(dfs, corruptStat, finalMissingBlksPerStrpCnt); if (corrupt) { incrCorruptCount(); if (!finalCountOnly && !finalListRecoverableFile) { unRecoverableFiles.add(corruptFileCandidate); } } else { if (!finalCountOnly && finalListRecoverableFile) { recoverableFiles.add(corruptFileCandidate); } } } catch (Throwable e) { LOG.error("Error in processing " + corruptFileCandidate, e); } } } finally { finishNum.incrementAndGet(); } } }; if (executor != null) { executor.execute(work); } else { work.run(); } } if (executor != null) { try { while (finishNum.get() < numThreads) { try { Thread.sleep(2000); } catch (InterruptedException ie) { LOG.warn("Raidfsck get exception ", ie); throw new IOException(ie); } } } finally { executor.shutdown(); // Waits for submitted tasks to finish. } } // If client is closed, fail the fsck check. if (!dfs.getClient().isOpen()) { throw new IOException("Filesystem closed."); } if (countOnly) { //Number of corrupt files (which cannot be fixed by Raid) out.println(getCorruptCount()); LOG.info("Nubmer of corrupt files:" + getCorruptCount()); //Number of files with at least one missing block out.println(corruptFileCandidates.size()); LOG.info("Number of files with at least one block missing/corrupt: " + corruptFileCandidates.size()); } else { if (listRecoverableFile) { for (String file : recoverableFiles) { out.println(file); } } else { for (String file : unRecoverableFiles) { out.println(file); } } } /*Number of stripes with missing blocks array, separated by each code id: * Number of missing blocks found from non-raided files. * codeId1 * index 0: Number of stripes found with one block missing in this fsck * index 1: Number of stripes found with two block missing in this fsck * and so on * codeId2 * index 0: Number of stripes found with one block missing in this fsck * index 1: Number of stripes found with two block missing in this fsck * and so on */ if (cntMissingBlksPerStrp) { out.println(this.numNonRaidedMissingBlks); for (String codecId : numStrpMissingBlksMap.keySet()) { out.println(codecId); AtomicLongArray numStrpMissingBlks = numStrpMissingBlksMap.get(codecId); for (int j = 0; j < numStrpMissingBlks.length(); j++) { long temp = numStrpMissingBlks.get(j); out.println(temp); LOG.info("Number of stripes with missing blocks at index " + j + " is " + temp); } } } }
From source file:com.yunmall.ymsdk.net.http.AsyncHttpClient.java
/** * Puts a new request in queue as a new thread in pool to be executed * * @param client HttpClient to be used for request, can differ in single requests * @param contentType MIME body type, for POST and PUT requests, may be null * @param context Context of Android application, to hold the reference of request * @param httpContext HttpContext in which the request will be executed * @param responseHandler ResponseHandler or its subclass to put the response into * @param uriRequest instance of HttpUriRequest, which means it must be of HttpDelete, * HttpPost, HttpGet, HttpPut, etc. * @return RequestHandle of future request process *///from w w w. j a v a 2 s . c o m protected RequestHandle sendRequest(DefaultHttpClient client, HttpContext httpContext, HttpUriRequest uriRequest, String contentType, ResponseHandlerInterface responseHandler, Context context) { if (uriRequest == null) { throw new IllegalArgumentException("HttpUriRequest must not be null"); } if (responseHandler == null) { throw new IllegalArgumentException("ResponseHandler must not be null"); } if (responseHandler.getUseSynchronousMode()) { throw new IllegalArgumentException( "Synchronous ResponseHandler used in AsyncHttpClient. You should create your response handler in a looper thread or use SyncHttpClient instead."); } if (contentType != null) { if (uriRequest instanceof HttpEntityEnclosingRequestBase && ((HttpEntityEnclosingRequestBase) uriRequest).getEntity() != null) { YmLog.w(LOG_TAG, "Passed contentType will be ignored because HttpEntity sets content type"); } else { uriRequest.setHeader(HEADER_CONTENT_TYPE, contentType); } } responseHandler.setRequestHeaders(uriRequest.getAllHeaders()); responseHandler.setRequestURI(uriRequest.getURI()); AsyncHttpRequest request = new AsyncHttpRequest(client, httpContext, uriRequest, responseHandler); threadPool.submit(request); RequestHandle requestHandle = new RequestHandle(request); if (context != null) { // Add request to request map List<RequestHandle> requestList = requestMap.get(context); synchronized (requestMap) { if (requestList == null) { requestList = Collections.synchronizedList(new LinkedList<RequestHandle>()); requestMap.put(context, requestList); } } if (responseHandler instanceof RangeFileAsyncHttpResponseHandler) ((RangeFileAsyncHttpResponseHandler) responseHandler).updateRequestHeaders(uriRequest); requestList.add(requestHandle); Iterator<RequestHandle> iterator = requestList.iterator(); while (iterator.hasNext()) { if (iterator.next().shouldBeGarbageCollected()) { iterator.remove(); } } } return requestHandle; }
From source file:org.eclipse.smarthome.binding.digitalstrom.internal.lib.structure.devices.impl.DeviceImpl.java
@Override public void enableSensorEchoBox() { if (sensorEchoBox == null) { sensorEchoBox = Collections.synchronizedList(new LinkedList<SensorEnum>()); }/*from ww w . j a v a 2 s . co m*/ }
From source file:com.fdwills.external.http.AsyncHttpClient.java
/** * Puts a new request in queue as a new thread in pool to be executed * * @param client HttpClient to be used for request, can differ in single requests * @param contentType MIME body type, for POST and PUT requests, may be null * @param context Context of Android application, to hold the reference of request * @param httpContext HttpContext in which the request will be executed * @param responseHandler ResponseHandler or its subclass to put the response into * @param uriRequest instance of HttpUriRequest, which means it must be of HttpDelete, * HttpPost, HttpGet, HttpPut, etc. * @return RequestHandle of future request process *///from w w w. ja va 2 s .c om protected RequestHandle sendRequest(DefaultHttpClient client, HttpContext httpContext, HttpUriRequest uriRequest, String contentType, ResponseHandlerInterface responseHandler, Context context) { if (uriRequest == null) { throw new IllegalArgumentException("HttpUriRequest must not be null"); } if (responseHandler == null) { throw new IllegalArgumentException("ResponseHandler must not be null"); } if (responseHandler.getUseSynchronousMode()) { throw new IllegalArgumentException( "Synchronous ResponseHandler used in AsyncHttpClient. You should create your response handler in a looper thread or use SyncHttpClient instead."); } if (contentType != null) { if (uriRequest instanceof HttpEntityEnclosingRequestBase && ((HttpEntityEnclosingRequestBase) uriRequest).getEntity() != null) { Log.w(LOG_TAG, "Passed contentType will be ignored because HttpEntity sets content type"); } else { uriRequest.setHeader(HEADER_CONTENT_TYPE, contentType); } } responseHandler.setRequestHeaders(uriRequest.getAllHeaders()); responseHandler.setRequestURI(uriRequest.getURI()); AsyncHttpRequest request = newAsyncHttpRequest(client, httpContext, uriRequest, contentType, responseHandler, context); threadPool.submit(request); RequestHandle requestHandle = new RequestHandle(request); if (context != null) { // Add request to request map List<RequestHandle> requestList = requestMap.get(context); synchronized (requestMap) { if (requestList == null) { requestList = Collections.synchronizedList(new LinkedList<RequestHandle>()); requestMap.put(context, requestList); } } requestList.add(requestHandle); Iterator<RequestHandle> iterator = requestList.iterator(); while (iterator.hasNext()) { if (iterator.next().shouldBeGarbageCollected()) { iterator.remove(); } } } return requestHandle; }
From source file:derson.com.httpsender.AsyncHttpClient.AsyncHttpClient.java
/** * Puts a new request in queue as a new thread in pool to be executed * * @param client HttpClient to be used for request, can differ in single requests * @param contentType MIME body type, for POST and PUT requests, may be null * @param context Context of Android application, to hold the reference of request * @param httpContext HttpContext in which the request will be executed * @param responseHandler ResponseHandler or its subclass to put the response into * @param uriRequest instance of HttpUriRequest, which means it must be of HttpDelete, * HttpPost, HttpGet, HttpPut, etc. * @return RequestHandle of future request process *///from w w w .j a va2 s . com protected RequestHandle sendRequest(DefaultHttpClient client, HttpContext httpContext, HttpUriRequest uriRequest, String contentType, ResponseHandlerInterface responseHandler, Context context) { if (uriRequest == null) { throw new IllegalArgumentException("HttpUriRequest must not be null"); } if (responseHandler == null) { throw new IllegalArgumentException("ResponseHandler must not be null"); } // if (responseHandler.getUseSynchronousMode()) { // throw new IllegalArgumentException("Synchronous ResponseHandler used in AsyncHttpClient. You should create your response handler in a looper thread or use SyncHttpClient instead."); // } if (contentType != null) { if (uriRequest instanceof HttpEntityEnclosingRequestBase && ((HttpEntityEnclosingRequestBase) uriRequest).getEntity() != null) { HPLog.w(LOG_TAG, "Passed contentType will be ignored because HttpEntity sets content type"); } else { uriRequest.setHeader(HEADER_CONTENT_TYPE, contentType); } } responseHandler.setRequestHeaders(uriRequest.getAllHeaders()); responseHandler.setRequestURI(uriRequest.getURI()); AsyncHttpRequest request = newAsyncHttpRequest(client, httpContext, uriRequest, contentType, responseHandler, context); threadPool.submit(request); RequestHandle requestHandle = new RequestHandle(request); if (context != null) { // Add request to request map List<RequestHandle> requestList = requestMap.get(context); synchronized (requestMap) { if (requestList == null) { requestList = Collections.synchronizedList(new LinkedList<RequestHandle>()); requestMap.put(context, requestList); } } requestList.add(requestHandle); Iterator<RequestHandle> iterator = requestList.iterator(); while (iterator.hasNext()) { if (iterator.next().shouldBeGarbageCollected()) { iterator.remove(); } } } return requestHandle; }