List of usage examples for java.util.concurrent Executors newSingleThreadExecutor
public static ExecutorService newSingleThreadExecutor()
From source file:com.grantingersoll.intell.clustering.KMeansClusteringEngine.java
public KMeansClusteringEngine() { execService = Executors.newSingleThreadExecutor(); measure = new CosineDistanceMeasure(); }
From source file:com.echopf.ECHODataObject.java
/** * Does Fetch data from the remote server in a background thread. * //from ww w .j a v a 2 s. co m * @param sync if set TRUE, then the main (UI) thread is waited for complete the fetching in a background thread. * (a synchronous communication) * @param callback invoked after the fetching is completed * @throws ECHOException */ protected void doFetch(final boolean sync, final FetchCallback<S> callback) throws ECHOException { final Handler handler = new Handler(); // Get ready a background thread ExecutorService executor = Executors.newSingleThreadExecutor(); Callable<Object> communictor = new Callable<Object>() { @Override public Object call() throws ECHOException { ECHOException exception = null; JSONObject data = null; try { synchronized (lock) { data = ECHOQuery.getRequest(getRequestURLPath()); copyData(data); } } catch (ECHOException e) { exception = e; } catch (Exception e) { exception = new ECHOException(e); } if (sync == false) { // Execute a callback method in the main (UI) thread. if (callback != null) { final ECHOException fException = exception; handler.post(new Runnable() { @Override @SuppressWarnings("unchecked") public void run() { callback.done((S) ECHODataObject.this, fException); } }); } } else { if (exception != null) throw exception; } return null; } }; Future<Object> future = executor.submit(communictor); if (sync) { try { future.get(); } catch (InterruptedException e) { Thread.currentThread().interrupt(); // ignore/reset } catch (ExecutionException e) { Throwable e2 = e.getCause(); if (e2 instanceof ECHOException) { throw (ECHOException) e2; } throw new RuntimeException(e2); } } }
From source file:com.netflix.curator.framework.recipes.barriers.TestDistributedBarrier.java
@Test public void testNoBarrier() throws Exception { CuratorFramework client = CuratorFrameworkFactory.newClient(server.getConnectString(), new RetryOneTime(1)); try {/*from w w w. j a va2 s .c o m*/ client.start(); final DistributedBarrier barrier = new DistributedBarrier(client, "/barrier"); Assert.assertTrue(barrier.waitOnBarrier(10, TimeUnit.SECONDS)); // just for grins, test the infinite wait ExecutorService service = Executors.newSingleThreadExecutor(); Future<Object> future = service.submit(new Callable<Object>() { @Override public Object call() throws Exception { barrier.waitOnBarrier(); return ""; } }); Assert.assertTrue(future.get(10, TimeUnit.SECONDS) != null); } finally { client.close(); } }
From source file:com.opengamma.bbg.replay.BloombergTickWriterTest.java
@Test(invocationCount = 5, successPercentage = 19) public void performance() throws Exception { ExecutorService writerExecutor = Executors.newSingleThreadExecutor(); Future<?> writerFuture = writerExecutor.submit(_writer); double nStartTime = System.currentTimeMillis(); //create ticks generators List<RandomTicksGeneratorJob> ticksGeneratorsList = new ArrayList<RandomTicksGeneratorJob>(); List<Thread> ticksGeneratorThreads = new ArrayList<Thread>(); for (int i = 0; i < TICKS_GENERATOR_THREAD_SIZE; i++) { RandomTicksGeneratorJob ticksGeneratorJob = new RandomTicksGeneratorJob( new ArrayList<String>(_ticker2buid.keySet()), _allTicksQueue); ticksGeneratorsList.add(ticksGeneratorJob); Thread thread = new Thread(ticksGeneratorJob, "TicksGenerator" + i); thread.start();/*from w w w . j a v a 2s . c o m*/ ticksGeneratorThreads.add(thread); } s_logger.info("Test running for 1min to gather stats"); Thread.sleep(RUN_DURATION); for (RandomTicksGeneratorJob ticksGeneratorJob : ticksGeneratorsList) { ticksGeneratorJob.terminate(); } //wait for all ticksGenerator threads to finish for (Thread thread : ticksGeneratorThreads) { thread.join(); } //send terminate message for tickWriter to terminate sendTerminateMessage(); //test should fail if writer throws an exception writerFuture.get(); writerExecutor.shutdown(); writerExecutor.awaitTermination(1, TimeUnit.SECONDS); double nRunDuration = System.currentTimeMillis() - nStartTime; double nTicks = ((double) _writer.getNTicks() / nRunDuration) * 1000; s_logger.info("ticks {}/s", nTicks); double nWrites = ((double) _writer.getNWrites() / nRunDuration) * 1000; s_logger.info("fileOperations {}/s", nWrites); double nBlocks = (double) _writer.getNBlocks() / (double) _writer.getNWrites(); s_logger.info("average blocks {}bytes", nBlocks); assertTrue("reportInterval > testRunTime", REPORT_INTERVAL > nRunDuration); if ((nWrites * nBlocks) < WRITER_SPEED_THRESHOLD) { s_logger.warn("BloombergTickWriter looks like running really slower than {}b/s", WRITER_SPEED_THRESHOLD); } }
From source file:fr.inria.wimmics.coresetimer.CoreseTimer.java
public CoreseTimer run() throws ClassNotFoundException, IllegalAccessException, InstantiationException, IOException, LoadException { LOGGER.entering(CoreseTimer.class.getName(), "run"); assert (initialized); // Loading the nq data in corese, then applying several times the query. LOGGER.log(Level.INFO, "beginning with input #{0}", test.getInput()); // require to have a brand new adapter for each new input set. adapter = (CoreseAdapter) Class.forName(adapterName).newInstance(); String inputFileName = ""; switch (mode) { case MEMORY: { inputFileName += test.getInput(); adapter.preProcessing(inputFileName, true); break;/*from w w w. ja va2s . co m*/ } case DB: { inputFileName += test.getInputDb(); System.setProperty("fr.inria.corese.tinkerpop.dbinput", inputFileName); adapter.preProcessing(inputFileName, false); break; } } String query = test.getRequest(); LOGGER.log(Level.INFO, "processing nbQuery #{0}", query); stats = new DescriptiveStatistics(); statsMemory = new DescriptiveStatistics(); int nbCycles = test.getMeasuredCycles() + test.getWarmupCycles(); boolean measured = true; for (int i = 0; i < nbCycles; i++) { LOGGER.log(Level.INFO, "iteration #{0}", i); System.gc(); final long startTime = System.currentTimeMillis(); LOGGER.log(Level.INFO, "before query"); ExecutorService executor = Executors.newSingleThreadExecutor(); Future<?> future = executor.submit(new Runnable() { @Override public void run() { adapter.execQuery(query); } }); try { future.get(1, TimeUnit.HOURS); measured = true; } catch (InterruptedException | TimeoutException e) { future.cancel(true); measured = false; LOGGER.log(Level.WARNING, "Terminated!"); } catch (ExecutionException ex) { Logger.getLogger(CoreseTimer.class.getName()).log(Level.SEVERE, null, ex); } executor.shutdownNow(); LOGGER.log(Level.INFO, "after query"); final long endTime = System.currentTimeMillis(); long delta = endTime - startTime; long memoryUsage = getMemoryUsage(); LOGGER.info(String.format("elapsed time = %d ms", delta)); LOGGER.info(String.format("used memory = %d bytes", memoryUsage)); if (i >= test.getWarmupCycles()) { if (!measured) { while (i < nbCycles) { stats.addValue(-100); statsMemory.addValue(memoryUsage); i++; } } else { stats.addValue(delta); statsMemory.addValue(memoryUsage); } } } adapter.saveResults(test.getOutputPath()); mappings = adapter.getMappings(); adapter.postProcessing(); LOGGER.exiting(CoreseTimer.class.getName(), "run"); return this; }
From source file:com.streamsets.datacollector.antennadoctor.storage.AntennaDoctorStorage.java
@Override protected void initTask() { LOG.info("Repository location: {}", repositoryDirectory); try {/*w ww. ja v a 2 s . c o m*/ // Make sure that we have our own directory to operate in if (!Files.exists(repositoryDirectory)) { Files.createDirectories(repositoryDirectory); } Path store = repositoryDirectory.resolve(AntennaDoctorConstants.FILE_DATABASE); if (!Files.exists(store)) { try (OutputStream stream = Files.newOutputStream(store)) { Resources.copy( Resources.getResource(AntennaDoctorStorage.class, AntennaDoctorConstants.FILE_DATABASE), stream); } } } catch (IOException e) { LOG.error("Cant initialize repository: {}", e.getMessage(), e); return; } // Schedule override runnable if allowed in configuration if (configuration.get(AntennaDoctorConstants.CONF_OVERRIDE_ENABLE, AntennaDoctorConstants.DEFAULT_OVERRIDE_ENABLE)) { LOG.info("Enabling polling of {} to override the rule database", AntennaDoctorConstants.FILE_OVERRIDE); this.executorService = Executors.newSingleThreadExecutor(); this.overrideRunnable = new OverrideFileRunnable(); this.future = executorService.submit(this.overrideRunnable); } // Remote repo handling if (configuration.get(AntennaDoctorConstants.CONF_UPDATE_ENABLE, AntennaDoctorConstants.DEFAULT_UPDATE_ENABLE)) { if (overrideRunnable != null) { LOG.info("Using override, not starting update thread."); } else { this.executorService = Executors.newSingleThreadScheduledExecutor(); this.updateRunnable = new UpdateRunnable(); this.future = ((ScheduledExecutorService) executorService).scheduleAtFixedRate(updateRunnable, configuration.get(AntennaDoctorConstants.CONF_UPDATE_DELAY, AntennaDoctorConstants.DEFAULT_UPDATE_DELAY), configuration.get(AntennaDoctorConstants.CONF_UPDATE_PERIOD, AntennaDoctorConstants.DEFAULT_UPDATE_PERIOD), TimeUnit.MINUTES); } } // And finally load rules delegate.loadNewRules(loadRules()); }
From source file:com.docd.purefm.adapters.BrowserBaseAdapter.java
/** * Sets and applies new data//w w w. jav a 2 s .c om * * @param data Data to apply */ public void updateData(GenericFile[] data) { if (mExecutor != null) { mExecutor.shutdownNow(); } mExecutor = Executors.newSingleThreadExecutor(); mContent.clear(); releaseObservers(); if (data != null) { Arrays.sort(data, mComparator.getComparator()); for (final GenericFile file : data) { mContent.add(file); final MultiListenerFileObserver observer = mObserverCache.getOrCreate(file, OBSERVER_EVENTS); observer.addOnEventListener(this); observer.startWatching(); mFileObservers.add(observer); } } this.notifyDataSetChanged(); }
From source file:de.tum.in.bluetooth.milling.machine.BluetoothMillingMachine.java
public BluetoothMillingMachine() { super(APP_ID); this.m_worker = Executors.newSingleThreadExecutor(); }
From source file:io.v.android.apps.reader.db.SyncbaseDB.java
@Override public void init(Activity activity) { // Make sure that the initialization logic runs at most once. if (mInitialized != null) { return;//w ww.j av a2 s . c om } mInitialized = SettableFuture.create(); if (mVContext == null) { if (activity instanceof VAndroidContextMixin) { // In case of the activity inherits from one of the baku-toolkit's base activities, // retrieve the Vanadium context from there directly. mVContext = ((VAndroidContextMixin) activity).getVAndroidContextTrait().getVContext(); } else { // Otherwise, initialize Vanadium runtime here with -vmodule=*=5 setting. if (DebugUtils.isApkDebug(activity)) { Options opts = new Options(); opts.set(OptionDefs.LOG_VMODULE, "*=5"); mVContext = V.init(mContext, opts); } else { mVContext = V.init(mContext); } } mVContext = V.withExecutor(mVContext, Executors.newSingleThreadExecutor()); try { mVContext = V.withListenSpec(mVContext, V.getListenSpec(mVContext).withProxy("proxy")); } catch (VException e) { handleError("Couldn't setup vanadium proxy: " + e.getMessage()); } } AccessList acl = new AccessList(ImmutableList.of(new BlessingPattern("...")), ImmutableList.<String>of()); mPermissions = new Permissions(ImmutableMap.of(Constants.READ.getValue(), acl, Constants.WRITE.getValue(), acl, Constants.ADMIN.getValue(), acl, Constants.RESOLVE.getValue(), acl, Constants.DEBUG.getValue(), acl)); getBlessings(activity); }
From source file:com.echopf.ECHOInstallation.java
/** * Does Get registration id from the GCM server in a background thread. * /*from w ww . j a v a 2 s .c o m*/ * @param sync if set TRUE, then the main (UI) thread is waited for complete the fetching in a background thread. * (a synchronous communication) * @param callback invoked after the getting is completed * @throws ECHOException */ protected void doGetRegistrationId(final boolean sync, final InstallationCallback callback) throws ECHOException { // if(!checkPlayServices(ECHO.context)) return; // Get senderId from AndroidManifest.xml String senderId = null; try { ApplicationInfo appInfo = ECHO.context.getPackageManager() .getApplicationInfo(ECHO.context.getPackageName(), PackageManager.GET_META_DATA); senderId = appInfo.metaData.getString(GCM_SENDER_ID_KEY); senderId = (senderId.startsWith("id:")) ? senderId.substring(3) : null; } catch (NameNotFoundException ignored) { // skip } if (senderId == null) throw new RuntimeException("`" + GCM_SENDER_ID_KEY + "` is not specified in `AndroidManifest.xml`."); // Get ready a background thread final Handler handler = new Handler(); final String fSenderId = senderId; ExecutorService executor = Executors.newSingleThreadExecutor(); Callable<Object> communictor = new Callable<Object>() { @Override public Object call() throws ECHOException { ECHOException exception = null; // InstanceID instanceID = InstanceID.getInstance(ECHO.context); String token = null; // Get updated InstanceID token. token = FirebaseInstanceId.getInstance().getToken(); // Log.d(TAG, "Refreshed token: " + refreshedToken); // TODO: Implement this method to send any registration to your app's servers. // token = instanceID.getToken(fSenderId, GoogleCloudMessaging.INSTANCE_ID_SCOPE); synchronized (lock) { deviceToken = token; } if (sync == false) { // Execute a callback method in the main (UI) thread. final ECHOException fException = exception; final String fToken = token; handler.post(new Runnable() { @Override public void run() { ECHOInstallation.this.deviceToken = fToken; callback.done(fException); } }); } else { if (exception != null) throw exception; } return null; } }; Future<Object> future = executor.submit(communictor); if (sync) { try { future.get(); } catch (InterruptedException e) { Thread.currentThread().interrupt(); // ignore/reset } catch (ExecutionException e) { Throwable e2 = e.getCause(); if (e2 instanceof ECHOException) { throw (ECHOException) e2; } throw new RuntimeException(e2); } } }