Example usage for java.util.concurrent Executors newSingleThreadExecutor

List of usage examples for java.util.concurrent Executors newSingleThreadExecutor

Introduction

In this page you can find the example usage for java.util.concurrent Executors newSingleThreadExecutor.

Prototype

public static ExecutorService newSingleThreadExecutor() 

Source Link

Document

Creates an Executor that uses a single worker thread operating off an unbounded queue.

Usage

From source file:com.ikanow.aleph2.management_db.services.SharedLibraryCrudService.java

/** Guice invoked constructor
 */// w  w  w .  j  a  va  2 s. c  om
@Inject
public SharedLibraryCrudService(final IServiceContext service_context) {
    _underlying_management_db = service_context.getServiceProvider(IManagementDbService.class, Optional.empty())
            .get();
    _storage_service = service_context.getServiceProvider(IStorageService.class, Optional.empty()).get();
    ModuleUtils.getAppInjector().thenRun(() -> {
        // (work around for guice initialization)
        _underlying_library_db.set(_underlying_management_db.get().getSharedLibraryStore());

        // Handle some simple optimization of the data bucket CRUD repo:
        Executors.newSingleThreadExecutor().submit(() -> {
            _underlying_library_db.get().optimizeQuery(Arrays.asList(
                    BeanTemplateUtils.from(SharedLibraryBean.class).field(SharedLibraryBean::path_name)));
        });
    });
}

From source file:com.github.google.beaconfig.BeaconConfigActivity.java

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_beacon_config);

    name = getIntent().getStringExtra(BeaconListAdapter.ViewHolder.BEACON_NAME);
    address = getIntent().getStringExtra(BeaconListAdapter.ViewHolder.BEACON_ADDRESS);

    setupToolbar(name, address);// ww w. j  ava2 s . c o  m
    setUpThrobber();
    executor = Executors.newSingleThreadExecutor();
    configurationsManager = new SavedConfigurationsManager(this);

    findViewById(R.id.grey_out_slot).setOnTouchListener(new View.OnTouchListener() {
        @Override
        public boolean onTouch(View view, MotionEvent motionEvent) {
            return swipeRefreshLayout.isRefreshing();
        }
    });

    accessBeacon();
}

From source file:com.amazon.alexa.avs.NotificationManager.java

NotificationManager(NotificationIndicator indicator, SimpleAudioPlayer audioPlayer, BasicHttpClient httpClient,
        FileDataStore<NotificationsStatePayload> dataStore) {
    this.notificationIndicator = indicator;
    this.player = audioPlayer;
    this.assets = Collections.synchronizedMap(new HashMap<String, File>());
    this.indicatorExecutor = Executors.newSingleThreadExecutor();
    this.assetDownloader = Executors.newCachedThreadPool();
    this.allowPersistentIndicator = new AtomicBoolean(true);
    this.httpClient = httpClient;
    this.isSetIndicatorPersisted = new AtomicBoolean(false);
    this.indicatorStatus = Status.NONE;
    this.dataStore = dataStore;
    this.indicatorFutures = Collections.synchronizedSet(new HashSet<Future<?>>());
    this.activeAudioAsset = new AtomicReference<String>("");
    this.resLoader = Thread.currentThread().getContextClassLoader();
}

From source file:org.wso2.carbon.automation.extensions.servers.httpserver.SimpleHttpServer.java

public void start() throws IOException {
    serverSocket = new ServerSocket(port);
    params = new BasicHttpParams();
    params.setIntParameter(CoreConnectionPNames.SO_TIMEOUT,
            getParameter(CoreConnectionPNames.SO_TIMEOUT, 60000))
            .setIntParameter(CoreConnectionPNames.SOCKET_BUFFER_SIZE,
                    getParameter(CoreConnectionPNames.SOCKET_BUFFER_SIZE, 8 * 1024))
            .setBooleanParameter(CoreConnectionPNames.STALE_CONNECTION_CHECK,
                    getParameter(CoreConnectionPNames.STALE_CONNECTION_CHECK, 0) == 1)
            .setBooleanParameter(CoreConnectionPNames.TCP_NODELAY,
                    getParameter(CoreConnectionPNames.TCP_NODELAY, 1) == 1)
            .setParameter(CoreProtocolPNames.ORIGIN_SERVER, "WSO2ESB-Test-Server");
    // Configure HTTP protocol processor
    BasicHttpProcessor httpProcessor = new BasicHttpProcessor();
    httpProcessor.addInterceptor(new ResponseDate());
    httpProcessor.addInterceptor(new ResponseServer());
    httpProcessor.addInterceptor(new ResponseContent());
    httpProcessor.addInterceptor(new ResponseConnControl());
    HttpRequestHandlerRegistry registry = new HttpRequestHandlerRegistry();
    registry.register("*", requestHandler);
    // Set up the HTTP service
    httpService = new HttpService(httpProcessor, new DefaultConnectionReuseStrategy(),
            new DefaultHttpResponseFactory(), registry, params);
    listener = Executors.newSingleThreadExecutor();
    workerPool = Executors.newFixedThreadPool(getParameter("ThreadCount", 2));
    shutdown = false;// w  w w  .  j a v a 2 s . c o  m
    listener.submit(new HttpListener());
}

From source file:gobblin.writer.http.AbstractHttpWriter.java

@SuppressWarnings("rawtypes")
public AbstractHttpWriter(AbstractHttpWriterBuilder builder) {
    super(builder.getState());
    this.log = builder.getLogger().isPresent() ? (Logger) builder.getLogger()
            : LoggerFactory.getLogger(this.getClass());
    this.debugLogEnabled = this.log.isDebugEnabled();

    HttpClientBuilder httpClientBuilder = builder.getHttpClientBuilder();
    httpClientBuilder.setConnectionManager(
            new HttpClientConnectionManagerWithConnTracking(builder.getHttpConnManager()));
    this.client = httpClientBuilder.build();
    this.singleThreadPool = MoreExecutors.listeningDecorator(Executors.newSingleThreadExecutor());

    if (builder.getSvcEndpoint().isPresent()) {
        setCurServerHost((URI) builder.getSvcEndpoint().get());
    }//from w  ww.ja va 2 s  .c  o m
}

From source file:com.streamsets.datacollector.lineage.LineagePublisherTaskImpl.java

@Override
protected void initTask() {
    String lineagePluginsConfig = configuration.get(LineagePublisherConstants.CONFIG_LINEAGE_PUBLISHERS, null);
    if (StringUtils.isEmpty(lineagePluginsConfig)) {
        LOG.info("No publishers configured");
        return;/*from  www  .  j ava2s  .com*/
    }

    String[] lineagePlugins = lineagePluginsConfig.split(",");
    // This implementation is intentionally limited to only one plugin at the moment
    if (lineagePlugins.length != 1) {
        throw new IllegalStateException("Only one lineage publisher is supported at the moment");
    }
    String publisherName = lineagePlugins[0];
    LineagePublisherDefinition def = getDefinition(publisherName);
    LOG.info("Using lineage publisher named {} (backed by {}::{})", publisherName,
            def.getLibraryDefinition().getName(), def.getName());

    // Instantiate and initialize the publisher
    createAndInitializeRuntime(def, publisherName);

    // Initialize blocking queue that will buffer data before sending them to lineage publisher
    int size = configuration.get(LineagePublisherConstants.CONFIG_LINEAGE_QUEUE_SIZE,
            LineagePublisherConstants.DEFAULT_LINEAGE_QUEUE_SIZE);
    eventQueue = new ArrayBlockingQueue<>(size);

    // And run the separate thread
    executorService = Executors.newSingleThreadExecutor();
    consumerRunnable = new EventQueueConsumer();
}

From source file:com.github.hronom.scrape.dat.website.controllers.ScrapeButtonController.java

public ActionListener createScrapeButtonActionListener() {
    return new ActionListener() {
        @Override//from w ww  . ja v  a2s  .  c o  m
        public void actionPerformed(ActionEvent event) {
            Executors.newSingleThreadExecutor().submit(new Runnable() {
                public void run() {
                    String selectedBrowserEngine = scrapeView.getSelectedBrowserEngine();
                    switch (selectedBrowserEngine) {
                    case "HtmlUnit":
                        processByHtmlUnit();
                        break;
                    case "Ui4j":
                        processByUi4j();
                        break;
                    case "JxBrowser":
                        processByJxBrowser();
                        break;
                    default:
                        logger.error("Unknown browser engine: " + selectedBrowserEngine);
                        break;
                    }
                }
            });
        }
    };
}

From source file:org.apache.hadoop.hdfs.qjournal.client.HttpImageUploadChannel.java

public HttpImageUploadChannel(String uri, String journalId, NamespaceInfo nsinfo, long txid, long epoch,
        int maxBufferedChunks) {
    this.uri = uri;
    this.journalId = journalId;
    this.namespaceInfoString = nsinfo.toColonSeparatedString();
    this.txid = txid;
    this.epoch = epoch;
    this.maxBufferedChunks = maxBufferedChunks;
    this.available = new Semaphore(maxBufferedChunks, true);

    sendExecutor = Executors.newSingleThreadExecutor();
}

From source file:edu.tamu.tcat.oss.account.test.mock.MockDataSource.java

public void activate() {
    try {/*from   w w  w .  ja v a  2 s  .c  o m*/

        String url = props.getPropertyValue(PROP_URL, String.class);
        String user = props.getPropertyValue(PROP_USER, String.class);
        String pass = props.getPropertyValue(PROP_PASS, String.class);

        Objects.requireNonNull(url, "Database connection URL not supplied");
        Objects.requireNonNull(user, "Database username not supplied");
        Objects.requireNonNull(pass, "Database password not supplied");

        int maxActive = getIntValue(props, PROP_MAX_ACTIVE, 30);
        int maxIdle = getIntValue(props, PROP_MAX_IDLE, 3);
        int minIdle = getIntValue(props, PROP_MIN_IDLE, 0);
        int minEviction = getIntValue(props, PROP_MIN_EVICTION, 10 * 1000);
        int betweenEviction = getIntValue(props, PROP_BETWEEN_EVICTION, 100);

        PostgreSqlDataSourceFactory factory = new PostgreSqlDataSourceFactory();
        PostgreSqlPropertiesBuilder builder = factory.getPropertiesBuilder().create(url, user, pass);
        dataSource = factory.getDataSource(builder.getProperties());

        //HACK: should add this API to the properties builder instead of downcasting and overriding
        {
            BasicDataSource basic = (BasicDataSource) dataSource;

            basic.setMaxActive(maxActive);
            basic.setMaxIdle(maxIdle);
            basic.setMinIdle(minIdle);
            basic.setMinEvictableIdleTimeMillis(minEviction);
            basic.setTimeBetweenEvictionRunsMillis(betweenEviction);
        }

        this.executor = Executors.newSingleThreadExecutor();
    } catch (Exception e) {
        throw new IllegalStateException("Failed initializing data source", e);
    }
}

From source file:no.ntnu.idi.socialhitchhiking.client.RequestTask.java

/**
 * Static method which adds elements and data to an xml file and sends it as a string to the server.
 * /*www  .  ja v  a  2 s  .  co m*/
 * @param req - {@link Request}
 * @return returns a subclass of {@link Response} to the input {@link Request}
 * @throws ClientProtocolException 
 * @throws MalformedURLException
 * @throws FileNotFoundException
 * @throws IOException
 * @throws ExecutionException 
 * @throws InterruptedException 
 */
public static Response sendRequest(final Request req, final Context c)
        throws ClientProtocolException, IOException, InterruptedException, ExecutionException {
    /**
     * Code for putting all all network communication on separate thread as required by higher Android APIs
     */
    ExecutorService executor = Executors.newSingleThreadExecutor();
    Callable<Response> callable = new Callable<Response>() {
        @Override
        /**
         * This contains the actual code for initiating the communication
         */
        public Response call() throws ClientProtocolException, IOException {
            String xml = RequestSerializer.serialize(req);
            con = c;
            String url = con.getResources().getString(R.string.server_url);
            RequestTask requestTask = new RequestTask(url, xml);

            return ResponseParser.parse(requestTask.getResponse());
        }
    };
    /**
     * Execute and retrieve result from network operation
     */
    Future<Response> future = executor.submit(callable);
    Response ret = future.get();
    executor.shutdown();
    return ret;
}