Java Code Examples for java.util.concurrent.Executors.newSingleThreadExecutor()

The following are Jave code examples for showing how to use newSingleThreadExecutor() of the java.util.concurrent.Executors class. You can vote up the examples you like. Your votes will be used in our system to get more good examples.
+ Save this method
Example 1
Project: minsx-java-example   File: SingleThreadPool.java   View Source Code Vote up 6 votes
public static void main(String args[]) {

        ExecutorService cachedThreadPool = Executors.newSingleThreadExecutor();

        for (int i = 0; i < 10; i++) {
            final int index = i;
            cachedThreadPool.execute(() -> {
                System.out.println("--->" + index);
                try {
                    Thread.sleep(3000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            });
        }

        System.out.println("-----------");

    }
 
Example 2
Project: data-queue   File: DataQueueExecutor.java   View Source Code Vote up 6 votes
/**
 * 向缓存文件中写入数据
 * @param data 待写入数据
 * @throws IOException
 */
public void offer(T data) throws IOException {
	logAccessFile.writeCacheAsJson(data);
	if (timeout){
		synchronized (lock) {
			if (pool == null || pool.isShutdown()) {
				pool = Executors.newSingleThreadExecutor();
			}
			if (future == null || future.isDone()){
				future = pool.submit(this);
			}
		}
	}else {
		if (pool == null || pool.isShutdown()) {
			pool = Executors.newSingleThreadExecutor();
		}
		if (future == null || future.isDone()){
			future = pool.submit(this);
		}
	}
}
 
Example 3
Project: FaceRecognition   File: MainActivity.java   View Source Code Vote up 6 votes
private void initView(){

        face1Result = (ImageView) findViewById(R.id.face1);
        btnToggleCamera = (ImageButton) findViewById(R.id.btnToggleCamera);
        btnGetFace = (ImageButton) findViewById(R.id.btnGetFace);
        btnGetInto = (Button) findViewById(R.id.btnGetInto);
        btnSignup =(Button) findViewById(R.id.btnsignup);
        surfaceView =  (SurfaceView) findViewById(R.id.surfaceView);
        surfaceHolder = surfaceView.getHolder();
        mGlobal = (Global) getApplicationContext();
        mInterface = new CameraInterface(MainActivity.this);
        executor = Executors.newSingleThreadExecutor();
        loader = Global.loader;
        faceView = (FaceView) findViewById(R.id.face_view);
        faceView = (FaceView) findViewById(R.id.face_view);

    }
 
Example 4
Project: illuminati   File: RabbitmqInfraTemplateImpl.java   View Source Code Vote up 6 votes
private void setBasicProperties () {
    final NioParams nioParams = new NioParams()
            .setNbIoThreads(1)
            .setWriteEnqueuingTimeoutInMs(0)
            .setWriteByteBufferSize(VALUE_SET_WRITE_BUFFER_SIZE);

    RABBITMQ_CONNECTION_FACTORY.useNio();
    RABBITMQ_CONNECTION_FACTORY.setNioParams(nioParams);
    RABBITMQ_CONNECTION_FACTORY.setConnectionTimeout(VALUE_CONNECTION_TIMEOUT_MS);
    RABBITMQ_CONNECTION_FACTORY.setChannelRpcTimeout(VALUE_RPC_CALL_TIMEOUT_MS);
    RABBITMQ_CONNECTION_FACTORY.setHandshakeTimeout(VALUE_HANDSHAKE_CONNECTION_TIMEOUT_MS);

    ExecutorService shutdownExecutor = Executors.newSingleThreadExecutor();
    RABBITMQ_CONNECTION_FACTORY.setShutdownExecutor(shutdownExecutor);

    RABBITMQ_CONNECTION_FACTORY.setShutdownTimeout(VALUE_SHUTDOWN_TIMEOUT_MS);
    RABBITMQ_CONNECTION_FACTORY.setRequestedHeartbeat(VALUE_REQUESTED_HEART_BEAT);
    RABBITMQ_CONNECTION_FACTORY.setAutomaticRecoveryEnabled(VALUE_AUTOMATIC_RECOVERY);
    RABBITMQ_CONNECTION_FACTORY.setTopologyRecoveryEnabled(VALUE_AUTOMATIC_EXCHANGE_RECOVERY);
    RABBITMQ_CONNECTION_FACTORY.setNetworkRecoveryInterval(VALUE_AUTOMATIC_RECOVERY_NETWORK_DELAY_MS);
    RABBITMQ_CONNECTION_FACTORY.setVirtualHost(this.virtualHost);
    RABBITMQ_CONNECTION_FACTORY.setSocketConfigurator(new DefaultSocketConfigurator() {
        @Override
        public void configure(Socket socket) throws IOException {
            socket.setTcpNoDelay(VALUE_DONT_USE_NAGLE);
            socket.setReceiveBufferSize(VALUE_SET_WRITE_BUFFER_SIZE);
            socket.setSendBufferSize(VALUE_SET_SEND_BUFFER_SIZE);
            socket.setPerformancePreferences(0, 2, 1);
            socket.setReuseAddress(true);
            socket.setKeepAlive(VALUE_TCP_KEELALIVE);
            socket.setSoLinger(true, 1000);
        }
    });
}
 
Example 5
Project: ETUmulator   File: UARTTest.java   View Source Code Vote up 6 votes
/**
 * Test of read method, of class UART.
 *
 * @throws java.lang.InterruptedException
 * @throws java.util.concurrent.ExecutionException
 * @throws java.util.concurrent.TimeoutException
 */
@Test
public void testRead() throws InterruptedException, ExecutionException, TimeoutException {
    ExecutorService executor = Executors.newSingleThreadExecutor();
    Semaphore semaphore = new Semaphore(0);
    mockInput = '5';
    Future<Void> future = executor.submit(() -> {
        ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(1);
        ScheduledFuture<?> releaserHandle = scheduler.schedule(() -> {
            semaphore.release();
        }, 5, TimeUnit.SECONDS);
        uart.read();
        releaserHandle.get(5, TimeUnit.SECONDS);
        return null;
    });
    semaphore.tryAcquire(15, TimeUnit.SECONDS);
    uart.feed(mockInput);
    future.get(25, TimeUnit.SECONDS);
    assertEquals("UART read result is wrong.", mockInput, registerFile.getValue("r0"));
}
 
Example 6
Project: stvs   File: EditorPaneController.java   View Source Code Vote up 6 votes
/**
 * <p>Creates the controller for the {@link EditorPane}.</p>
 *
 * @param code         the code file to be shown
 * @param globalConfig the global configuration (for font size or style)
 */
public EditorPaneController(Code code, GlobalConfig globalConfig) {
    this.code = code;
    this.view = new EditorPane(code.getSourcecode(),
            code.syntaxErrorsProperty());
    this.globalConfig = globalConfig;
    this.globalConfig.showLineNumbersProperty()
            .addListener(new ShowLineNumbersListener());
    this.view.getStylesheets()
            .add(EditorPane.class.getResource("st-keywords.css")
                    .toExternalForm());
    this.executor = Executors.newSingleThreadExecutor();
    configureTextArea();
    setupContextMenu();
    handleTextChange(computeHighlighting(code.getSourcecode()));
    this.globalConfig.editorFontSizeProperty().addListener(
            (observable, oldValue, newValue) -> updateFontSize(
                    newValue.intValue()));
    this.globalConfig.editorFontFamilyProperty().addListener(
            (observable, oldValue, newValue) -> updateFontFamily(newValue));
    updateFontFamily(globalConfig.getEditorFontFamily());
    updateFontSize(globalConfig.getEditorFontSize());
    filterAltEvents();
}
 
Example 7
Project: https-github.com-hyb1996-NoRootScriptDroid   File: AccessibilityService.java   View Source Code Vote up 5 votes
@Override
protected boolean onKeyEvent(final KeyEvent event) {
    if (mKeyEventExecutor == null) {
        mKeyEventExecutor = Executors.newSingleThreadExecutor();
    }
    mKeyEventExecutor.execute(new Runnable() {
        @Override
        public void run() {
            stickOnKeyObserver.onKeyEvent(event.getKeyCode(), event);
            mOnKeyObserver.onKeyEvent(event.getKeyCode(), event);
        }
    });
    return false;
}
 
Example 8
Project: NioSmtpClient   File: SmtpSessionTest.java   View Source Code Vote up 5 votes
@Test
public void itExecutesReturnedExceptionalFuturesOnTheProvidedExecutor() {
  ExecutorService executorService = Executors.newSingleThreadExecutor(new ThreadFactoryBuilder().setNameFormat("SmtpSessionTestExecutor").build());
  SmtpSession session = new SmtpSession(channel, responseHandler, CONFIG, executorService, SSL_ENGINE_SUPPLIER);

  CompletableFuture<SmtpClientResponse> future = session.send(SMTP_REQUEST);
  CompletableFuture<Boolean> assertionFuture = future.handle((r, e) -> {
    assertThat(Thread.currentThread().getName()).contains("SmtpSessionTestExecutor");
    return true;
  });

  responseFuture.completeExceptionally(new RuntimeException());
  assertionFuture.join();
}
 
Example 9
Project: syndesis   File: DefaultProjectGenerator.java   View Source Code Vote up 5 votes
@SuppressWarnings("resource")
@Override
public InputStream generate(Integration integration) throws IOException {
    final PipedInputStream is = new PipedInputStream();
    final ExecutorService executor = Executors.newSingleThreadExecutor();
    final PipedOutputStream os = new PipedOutputStream(is);

    executor.execute(generateAddProjectTarEntries(integration, os));

    return is;
}
 
Example 10
Project: neoscada   File: Activator.java   View Source Code Vote up 5 votes
@Override
public void start ( final BundleContext bundleContext ) throws Exception
{
    Activator.context = bundleContext;
    this.executor = Executors.newSingleThreadExecutor ( new NamedThreadFactory ( "HistoricalProxyItem" ) );
    this.service = new ProxyItemFactory ( bundleContext, this.executor );

    final Dictionary<String, Object> properties = new Hashtable<String, Object> ();
    properties.put ( Constants.SERVICE_VENDOR, "Eclipse SCADA Project" );
    properties.put ( Constants.SERVICE_DESCRIPTION, "A historical item that proxies access to a set of other items at the same time, merging the result based on the quality." );
    properties.put ( ConfigurationAdministrator.FACTORY_ID, "org.eclipse.scada.hd.server.proxy" );
    bundleContext.registerService ( ConfigurationFactory.class.getName (), this.service, properties );
}
 
Example 11
Project: chromium-net-for-android   File: CronetSampleActivity.java   View Source Code Vote up 5 votes
private void startWithURL(String url, String postData) {
    Log.i(TAG, "Cronet started: %s", url);
    mUrl = url;

    Executor executor = Executors.newSingleThreadExecutor();
    UrlRequest.Callback callback = new SimpleUrlRequestCallback();
    UrlRequest.Builder builder = new UrlRequest.Builder(url, callback, executor, mCronetEngine);
    applyPostDataToUrlRequestBuilder(builder, executor, postData);
    builder.build().start();
}
 
Example 12
Project: openjdk-jdk10   File: EditorTestBase.java   View Source Code Vote up 4 votes
public static ExecutorService getExecutor() {
    if (executor == null) {
        executor = Executors.newSingleThreadExecutor();
    }
    return executor;
}
 
Example 13
Project: incubator-netbeans   File: LiveCPUView.java   View Source Code Vote up 4 votes
private synchronized ExecutorService getExecutor() {
    if (executor == null) executor = Executors.newSingleThreadExecutor();
    return executor;
}
 
Example 14
Project: ucar-weex-core   File: WXWorkThreadManager.java   View Source Code Vote up 4 votes
public WXWorkThreadManager() {
  singleThreadExecutor = Executors.newSingleThreadExecutor();
}
 
Example 15
Project: nc-android-webrtcpeer   File: PeerConnectionClient.java   View Source Code Vote up 4 votes
private PeerConnectionClient() {
    // Executor thread is started once in private ctor and is used for all
    // peer connection API calls to ensure new peer connection factory is
    // created on the same thread as previously destroyed factory.
    executor = Executors.newSingleThreadExecutor();
}
 
Example 16
Project: j1st-mqtt   File: HazelcastBrokerCommunicator.java   View Source Code Vote up 4 votes
@Override
public void init(AbstractConfiguration config, String brokerId, BrokerListenerFactory factory) {
    this.hazelcast = Hazelcast.newHazelcastInstance();

    logger.trace("Initializing Hazelcast broker resources ...");

    BROKER_TOPIC_PREFIX = config.getString("communicator.broker.topic");
    this.brokerRing = this.hazelcast.getRingbuffer(BROKER_TOPIC_PREFIX + "." + brokerId);

    logger.trace("Initializing Hazelcast application resources ...");

    this.applicationRing = this.hazelcast.getRingbuffer(config.getString("communicator.application.topic"));

    logger.trace("Initializing Hazelcast broker consumer's workers ...");

    // consumer executor
    this.executor = Executors.newSingleThreadExecutor();
    this.executor.submit(new HazelcastBrokerWorker(this.brokerRing, factory.newListener()));
}
 
Example 17
Project: HDImageView   File: HDImageView.java   View Source Code Vote up 4 votes
private void init(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {

        HDImageViewFactory.initializeDefault(context);

        //init
        mDensity = context.getResources().getDisplayMetrics().density;
        createPaints();

        mBitmapDataSource = new DefaultBitmapDataSource();
        mScaleAnimationInterpolator = HDImageViewFactory.getInstance().getScaleAnimationInterpolator();
        mTranslationAnimationInterpolator = HDImageViewFactory.getInstance().getTranslationAnimationInterpolator();

        mOriginalHandler = new OriginalHandler(this);
        mOriginalExecutor = Executors.newSingleThreadExecutor();
        setMinimumDpi(160);
        setDoubleTapZoomDpi(160);
        setWillNotDraw(false);
        setGestureDetector(context);

        if (attrs != null){
            TypedArray typedArray = getContext().obtainStyledAttributes(attrs, R.styleable.HDImageView,defStyleAttr,0);

            mDuration = typedArray.getInt(R.styleable.HDImageView_duration,DEFAULT_DURATION);

            int resId = typedArray.getResourceId(R.styleable.HDImageView_src,NO_ID);
            if (resId != NO_ID){
                setImageSource(ImageSourceBuilder.newBuilder().setUri(resId).build());
            }

            boolean translateEnabled = typedArray.getBoolean(R.styleable.HDImageView_translateEnabled,true);
            setTranslateEnabled(translateEnabled);

            boolean zoomEnabled = typedArray.getBoolean(R.styleable.HDImageView_zoomEnabled,true);
            setZoomEnabled(zoomEnabled);

            boolean quickScaleEnabled = typedArray.getBoolean(R.styleable.HDImageView_quickScaleEnabled,true);
            setQuickScaleEnabled(quickScaleEnabled);

            int mappingBackgroundColor = typedArray.getColor(R.styleable.HDImageView_mappingBackgroundColor, Color.TRANSPARENT);
            setMappingBackgroundColor(mappingBackgroundColor);

            typedArray.recycle();
        }
    }
 
Example 18
Project: flume-release-1.7.0   File: TestBucketWriter.java   View Source Code Vote up 4 votes
@Test
public void testIntervalRoller() throws IOException, InterruptedException {
  final int ROLL_INTERVAL = 1; // seconds
  final int NUM_EVENTS = 10;
  final AtomicBoolean calledBack = new AtomicBoolean(false);

  MockHDFSWriter hdfsWriter = new MockHDFSWriter();
  BucketWriter bucketWriter = new BucketWriter(
      ROLL_INTERVAL, 0, 0, 0, ctx, "/tmp", "file", "", ".tmp", null, null,
      SequenceFile.CompressionType.NONE, hdfsWriter, timedRollerPool, proxy,
      new SinkCounter("test-bucket-writer-" + System.currentTimeMillis()), 0,
      new HDFSEventSink.WriterCallback() {
        @Override
        public void run(String filePath) {
          calledBack.set(true);
        }
      }, null, 30000, Executors.newSingleThreadExecutor(), 0, 0);

  Event e = EventBuilder.withBody("foo", Charsets.UTF_8);
  long startNanos = System.nanoTime();
  for (int i = 0; i < NUM_EVENTS - 1; i++) {
    bucketWriter.append(e);
  }

  // sleep to force a roll... wait 2x interval just to be sure
  Thread.sleep(2 * ROLL_INTERVAL * 1000L);

  Assert.assertTrue(bucketWriter.closed);
  Assert.assertTrue(calledBack.get());

  bucketWriter = new BucketWriter(
      ROLL_INTERVAL, 0, 0, 0, ctx, "/tmp", "file", "", ".tmp", null, null,
      SequenceFile.CompressionType.NONE, hdfsWriter, timedRollerPool, proxy,
      new SinkCounter("test-bucket-writer-" + System.currentTimeMillis()), 0, null, null, 30000,
      Executors.newSingleThreadExecutor(), 0, 0);
  // write one more event (to reopen a new file so we will roll again later)
  bucketWriter.append(e);

  long elapsedMillis = TimeUnit.MILLISECONDS.convert(
      System.nanoTime() - startNanos, TimeUnit.NANOSECONDS);
  long elapsedSeconds = elapsedMillis / 1000L;

  logger.info("Time elapsed: {} milliseconds", elapsedMillis);
  logger.info("Number of events written: {}", hdfsWriter.getEventsWritten());
  logger.info("Number of bytes written: {}", hdfsWriter.getBytesWritten());
  logger.info("Number of files opened: {}", hdfsWriter.getFilesOpened());
  logger.info("Number of files closed: {}", hdfsWriter.getFilesClosed());

  Assert.assertEquals("events written", NUM_EVENTS,
      hdfsWriter.getEventsWritten());
  Assert.assertEquals("bytes written", e.getBody().length * NUM_EVENTS,
      hdfsWriter.getBytesWritten());
  Assert.assertEquals("files opened", 2, hdfsWriter.getFilesOpened());

  // before auto-roll
  Assert.assertEquals("files closed", 1, hdfsWriter.getFilesClosed());

  logger.info("Waiting for roll...");
  Thread.sleep(2 * ROLL_INTERVAL * 1000L);

  logger.info("Number of files closed: {}", hdfsWriter.getFilesClosed());
  Assert.assertEquals("files closed", 2, hdfsWriter.getFilesClosed());
}
 
Example 19
Project: Achilles_Android   File: MainActivity.java   View Source Code Vote up 4 votes
private void init() {
    mLocalVideoView = (SurfaceViewRenderer) findViewById(R.id.local_video_view);

    // Init ExecutorService
    mExecutorService = Executors.newSingleThreadExecutor();

    // Socket.IO initialization
    initSocket();

    // Create video renderer
    rootEglBase = EglBase.create();
    Log.d(TAG, "Created video renderer.");

    mLocalVideoView.init(rootEglBase.getEglBaseContext(), null);
    mLocalVideoView.setScalingType(RendererCommon.ScalingType.SCALE_ASPECT_FILL);
    mLocalVideoView.setEnableHardwareScaler(true);
    // Set ProxyRenderer target to SurfaceViewRenderer
    localProxyRenderer.setTarget(mLocalVideoView);
    mLocalVideoView.setMirror(true);

    // Check permission
    /*for (String permission : MANDATORY_PERMISSIONS) {
        if (checkCallingOrSelfPermission(permission) != PackageManager.PERMISSION_GRANTED) {
            Log.w(TAG, "Permission " + permission + " is not granted.");
            // finish();
            return;
        }
    }*/

    DisplayMetrics displayMetrics = getDisplayMetrics();
    videoWidth = displayMetrics.widthPixels;
    videoHeight = displayMetrics.heightPixels;
    videoFps = 30;

    initPeerConnectionFactory();

    // Set STUN Server
    mIceServers.add(new PeerConnection.IceServer(googleStunServer));

    // Set default SessionDescription MediaConstraints
    mSdpConstraints.mandatory.add(new MediaConstraints.KeyValuePair("OfferToReceiveAudio", "true"));
    mSdpConstraints.mandatory.add(new MediaConstraints.KeyValuePair("OfferToReceiveVideo", "true"));

    // Set default AudioConstraints
    mAudioConstraints.mandatory.add(new MediaConstraints.KeyValuePair(AUDIO_ECHO_CANCELLATION_CONSTRAINT, "false"));
    mAudioConstraints.mandatory.add(new MediaConstraints.KeyValuePair(AUDIO_AUTO_GAIN_CONTROL_CONSTRAINT, "false"));
    mAudioConstraints.mandatory.add(new MediaConstraints.KeyValuePair(AUDIO_HIGH_PASS_FILTER_CONSTRAINT, "false"));
    mAudioConstraints.mandatory.add(new MediaConstraints.KeyValuePair(AUDIO_NOISE_SUPPRESSION_CONSTRAINT, "false"));

    // Enalble DTLS for normal calls
    mPcConstraints.optional.add(new MediaConstraints.KeyValuePair("RtpDataChannels", "true"));
}
 
Example 20
Project: uavstack   File: IssueDiagnoseAssitAgent.java   View Source Code Vote up 3 votes
@Override
public void start() {

    wdh = new DataWormHoleWorker("DataWormHoleWorker", this.feature, "dwhhandlers");

    wdhThread = Executors.newSingleThreadExecutor();

    wdhThread.execute(wdh);

    if (log.isTraceEnable()) {
        log.info(this, "DataWormHoleWorker started");
    }
}