List of usage examples for java.util.concurrent Executors newSingleThreadExecutor
public static ExecutorService newSingleThreadExecutor()
From source file:com.cognifide.actions.msg.websocket.client.SocketClient.java
private void startLoops() { for (AgentConfig config : agentConfigManager.getConfigurations().values()) { if (config.isEnabled() && config.usedForReverseReplication()) { try { final SocketClientRunnable loop = createLoop(config); Executors.newSingleThreadExecutor().execute(loop); loops.add(loop);/*from w w w .j a v a 2 s.com*/ } catch (URISyntaxException e) { LOG.error("Can't parse agent url: " + config.getTransportURI(), e); } } } }
From source file:com.zxy.commons.mq.consumer.AbstractConsumer.java
/** * // ww w. j av a2s . c o m * * @param groupId groupId * @param topic topic * @param threadNum thread number */ public AbstractConsumer(String groupId, String topic, Integer threadNum) { this.topic = topic; if (threadNum != null) { this.threadNum = threadNum; this.executor = Executors.newFixedThreadPool(threadNum); } else { this.threadNum = 1; this.executor = Executors.newSingleThreadExecutor(); } Properties props = new Properties(); props.put("zookeeper.connect", PROP.getZookeeperConnect()); props.put("group.id", groupId); props.put("zookeeper.session.timeout.ms", PROP.getZookeeperSessionTimeout()); props.put("zookeeper.sync.time.ms", PROP.getZookeeperSyncTime()); props.put("auto.commit.interval.ms", PROP.getAutoCommitInterval()); String autoCommitEnable = PROP.getAutoCommitEnable(); if (StringUtils.isNotBlank(autoCommitEnable)) { props.put("auto.commit.enable", autoCommitEnable); } consumer = kafka.consumer.Consumer.createJavaConsumerConnector(new ConsumerConfig(props)); }
From source file:com.predic8.membrane.core.CoreActivator.java
public void start(BundleContext context) throws Exception { super.start(context); plugin = this; pluginLogger = CoreActivator.getDefault().getLog(); //String path = new File(FileLocator.resolve(CoreActivator.getDefault().getBundle().getEntry("/")).getPath()).getAbsolutePath(); final MembraneCommandLine cl = new MembraneCommandLine(); cl.parse(fixArguments(Platform.getCommandLineArgs())); if (cl.hasMonitorBeans()) { log.info("loading monitor beans from command line argument: " + cl.getMonitorBeans()); Router.init(FileUtil.prefixMembraneHomeIfNeeded(new File(cl.getMonitorBeans())).getAbsolutePath(), this.getClass().getClassLoader()); } else {//from ww w. ja v a2s . co m try { if (ClassloaderUtil.fileExists(getMonitorBeansFileName())) { info("Eclipse framework found config file: " + getMonitorBeansFileName()); readBeanConfigWhenStartedAsProduct(); } else { readBeanConfigWhenStartedInEclipse(); } } catch (Exception e1) { error("Unable to read bean configuration file: " + e1.getMessage()); error("Unable to read bean configuration file: " + e1.getStackTrace()); e1.printStackTrace(); } } Executors.newSingleThreadExecutor().execute(new Runnable() { public void run() { try { Router.getInstance().getConfigurationManager().loadConfiguration(getConfigurationFileName(cl)); } catch (Exception e) { log.warn("no configuration loaded", e); // we ignore this exception because the monitor can start up // without loading a rules configuration // we need to throw an exception because the router must display an error message } } private String getConfigurationFileName(MembraneCommandLine cl) { if (cl.hasConfiguration()) { log.info("loading configuration from command line argument: " + cl.getConfiguration()); return FileUtil.prefixMembraneHomeIfNeeded(new File(cl.getConfiguration())).getAbsolutePath(); } return System.getProperty("user.home") + System.getProperty("file.separator") + ".membrane.xml"; } }); }
From source file:com.github.google.beaconfig.ScanningActivity.java
@Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar); setSupportActionBar(toolbar);//from w w w . j a v a 2 s . c o m new SavedConfigurationsManager(this).initialiseConfigurationSaving(); executor = Executors.newSingleThreadExecutor(); beaconsListAdapter = new BeaconListAdapter(new ArrayList<BeaconScanData>(), getApplication()); RecyclerView beaconsRecyclerView = (RecyclerView) findViewById(R.id.rv); beaconsRecyclerView.setAdapter(beaconsListAdapter); beaconsRecyclerView.setLayoutManager(new LinearLayoutManager(getApplicationContext())); final FloatingActionButton refresh = (FloatingActionButton) findViewById(R.id.fab); refresh.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { scan(); } }); setUpThrobber(); getRequiredPermissions(); beaconsRecyclerView.setOnTouchListener(new View.OnTouchListener() { @Override public boolean onTouch(View view, MotionEvent motionEvent) { return swipeRefreshLayout.isRefreshing(); } }); beaconsRecyclerView.addOnItemTouchListener(new RecyclerView.OnItemTouchListener() { @Override public boolean onInterceptTouchEvent(RecyclerView rv, MotionEvent e) { Log.d(TAG, "On interception touch listener " + swipeRefreshLayout.isRefreshing()); return swipeRefreshLayout.isRefreshing(); } @Override public void onTouchEvent(RecyclerView rv, MotionEvent e) { } @Override public void onRequestDisallowInterceptTouchEvent(boolean disallowIntercept) { } }); }
From source file:com.github.brandtg.switchboard.MysqlLogPuller.java
/** * Starts pulling events from switchboard server. *///from ww w . j a v a 2 s . c o m public void start() throws Exception { if (!isStarted.getAndSet(true)) { outputStream.connect(inputStream); callbackExecutor = Executors.newSingleThreadExecutor(); refreshExecutor = Executors.newSingleThreadExecutor(); eventExecutors = new NioEventLoopGroup(); // Start server to receive log segments logReceiver = new LogReceiver(sinkAddress, eventExecutors, outputStream); logReceiver.start(); // Iterates through events and fires appropriate callbacks callbackExecutor.submit(getCallback()); // Pulls log indexes logPuller = new LogPuller(sourceAddress, sinkAddress, database, lastIndex); logReceiver.registerListener(logPuller); refreshExecutor.submit(logPuller); } }
From source file:com.example.android.codelabs.agera.step3.CalculatorActivityFinal.java
@Override protected void onStart() { super.onStart(); mExecutor = Executors.newSingleThreadExecutor(); mResultRepository = Repositories.repositoryWithInitialValue(Result.<String>absent()) .observe(mValue1Repo, mValue2Repo, mOperationSelector).onUpdatesPerLoop().goTo(mExecutor) .attemptTransform(CalculatorOperations::keepCpuBusy).orEnd(Result::failure).getFrom(mValue1Repo) .mergeIn(mValue2Repo, Pair::create) .attemptMergeIn(mOperationSelector, CalculatorOperations::attemptOperation).orEnd(Result::failure) .thenTransform(input -> Result.present(input.toString())) .onConcurrentUpdate(RepositoryConfig.SEND_INTERRUPT).compile(); ((SeekBar) findViewById(R.id.seekBar1)) .setOnSeekBarChangeListener(new RepositorySeekBarListener(mValue1Repo)); ((SeekBar) findViewById(R.id.seekBar2)) .setOnSeekBarChangeListener(new RepositorySeekBarListener(mValue2Repo)); mValue1TVupdatable = () -> ((TextView) findViewById(R.id.value1)).setText(mValue1Repo.get().toString()); mValue2TVupdatable = () -> ((TextView) findViewById(R.id.value2)).setText(mValue2Repo.get().toString()); TextView resultTextView = (TextView) findViewById(R.id.textViewResult); mResultUpdatable = () -> mResultRepository.get() .ifFailedSendTo(t -> Toast.makeText(this, t.getLocalizedMessage(), Toast.LENGTH_SHORT).show()) .ifFailedSendTo(t -> {// w ww. j ava 2 s. c om if (t instanceof ArithmeticException) { resultTextView.setText("DIV#0"); } else { resultTextView.setText("N/A"); } }).ifSucceededSendTo(resultTextView::setText); setUpdatables(); }
From source file:net.openid.appauthdemo.TokenActivity.java
@Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); mStateManager = AuthStateManager.getInstance(this); mExecutor = Executors.newSingleThreadExecutor(); Configuration config = Configuration.getInstance(this); if (config.hasConfigurationChanged()) { Toast.makeText(this, "Configuration change detected", Toast.LENGTH_SHORT).show(); signOut();/* w w w . ja v a2 s . com*/ return; } mAuthService = new AuthorizationService(this, new AppAuthConfiguration.Builder().setConnectionBuilder(config.getConnectionBuilder()).build()); setContentView(R.layout.activity_token); displayLoading("Restoring state..."); if (savedInstanceState != null) { try { mUserInfoJson.set(new JSONObject(savedInstanceState.getString(KEY_USER_INFO))); } catch (JSONException ex) { Log.e(TAG, "Failed to parse saved user info JSON, discarding", ex); } } }
From source file:edu.vt.middleware.cas.ldap.LoadDriver.java
public LoadDriver(final int sampleCount, final int workerCount, final File credentialsFile, final ApplicationContext context) { this.credentialsFile = credentialsFile; this.resultExecutor = Executors.newSingleThreadExecutor(); this.workExecutor = Executors.newFixedThreadPool(workerCount); this.context = context; final AuthenticationHandler handler = this.context.getBean(AuthenticationHandler.class); if (handler == null) { throw new IllegalStateException("AuthenticationHandler bean not found."); }//from ww w .j a v a2 s .co m if (!handler.supports(new UsernamePasswordCredentials())) { throw new IllegalStateException("AuthenticationHandler bean does not support password authentication"); } this.state.setWorkQueue(new ArrayBlockingQueue<UsernamePasswordCredentials>(sampleCount)); this.state.setResultQueue(new ArrayBlockingQueue<Sample>(sampleCount)); this.state.setAuthenticationHandler(handler); }
From source file:com.github.c77.base_driver.kobuki.KobukiBaseDevice.java
public KobukiBaseDevice(UsbSerialDriver driver) throws Exception { if (driver == null) { throw new Exception("null USB driver provided"); }//from ww w. ja va 2 s. com serialDriver = driver; try { serialDriver.open(); serialDriver.setParameters(115200, UsbSerialDriver.DATABITS_8, UsbSerialDriver.STOPBITS_1, UsbSerialDriver.PARITY_NONE); } catch (IOException e) { log.info("Error setting up device: " + e.getMessage(), e); try { serialDriver.close(); } catch (IOException e1) { e1.printStackTrace(); } } final ExecutorService executorService = Executors.newSingleThreadExecutor(); SerialInputOutputManager serialInputOutputManager; final SerialInputOutputManager.Listener listener = new SerialInputOutputManager.Listener() { @Override public void onRunError(Exception e) { } @Override public void onNewData(final byte[] data) { KobukiBaseDevice.this.updateReceivedData(data); } }; serialInputOutputManager = new SerialInputOutputManager(serialDriver, listener); executorService.submit(serialInputOutputManager); }
From source file:com.github.c77.base_driver.husky.HuskyBaseDevice.java
public HuskyBaseDevice(UsbSerialDriver driver) { // Initialize timestamp for messages to be written to the Husky base initialTime = System.currentTimeMillis(); // Open and initialize the underlying USB-serial driver serialDriver = driver;//from ww w. j ava2 s . co m try { serialDriver.open(); serialDriver.setParameters(115200, UsbSerialDriver.DATABITS_8, UsbSerialDriver.STOPBITS_1, UsbSerialDriver.PARITY_NONE); log.info("Serial device opened correctly"); } catch (IOException e) { log.error("Error setting up device: " + e.getMessage(), e); try { serialDriver.close(); } catch (Throwable t) { } throw new RuntimeException("Couldn't open USB device driver", e); } // Listen for USB-serial input events and call updateReceivedData whenever new data // is received final ExecutorService executorService = Executors.newSingleThreadExecutor(); SerialInputOutputManager serialInputOutputManager; final SerialInputOutputManager.Listener listener = new SerialInputOutputManager.Listener() { @Override public void onRunError(Exception e) { } @Override public void onNewData(final byte[] data) { HuskyBaseDevice.this.updateReceivedData(data); } }; serialInputOutputManager = new SerialInputOutputManager(serialDriver, listener); executorService.submit(serialInputOutputManager); }