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:info.batey.kafka.unit.KafkaUnit.java

private <T> List<T> readMessages(String topicName, final MessageExtractor<T> messageExtractor)
        throws TimeoutException {
    ExecutorService singleThread = Executors.newSingleThreadExecutor();
    Properties consumerProperties = new Properties();
    consumerProperties.put("zookeeper.connect", zookeeperString);
    consumerProperties.put("group.id", "10");
    consumerProperties.put("socket.timeout.ms", "500");
    consumerProperties.put("consumer.id", "test");
    consumerProperties.put("auto.offset.reset", "smallest");
    consumerProperties.put("consumer.timeout.ms", "500");
    ConsumerConnector javaConsumerConnector = Consumer
            .createJavaConsumerConnector(new ConsumerConfig(consumerProperties));
    StringDecoder stringDecoder = new StringDecoder(new VerifiableProperties(new Properties()));
    Map<String, Integer> topicMap = new HashMap<>();
    topicMap.put(topicName, 1);/*from   ww w .  j  a  v  a 2  s . c  o  m*/
    Map<String, List<KafkaStream<String, String>>> events = javaConsumerConnector.createMessageStreams(topicMap,
            stringDecoder, stringDecoder);
    List<KafkaStream<String, String>> events1 = events.get(topicName);
    final KafkaStream<String, String> kafkaStreams = events1.get(0);

    Future<List<T>> submit = singleThread.submit(new Callable<List<T>>() {
        public List<T> call() throws Exception {
            List<T> messages = new ArrayList<>();
            try {
                for (MessageAndMetadata<String, String> kafkaStream : kafkaStreams) {
                    T message = messageExtractor.extract(kafkaStream);
                    LOGGER.info("Received message: {}", kafkaStream.message());
                    messages.add(message);
                }
            } catch (ConsumerTimeoutException e) {
                // always gets throws reaching the end of the stream
            }
            return messages;
        }
    });

    List<T> receivedMessages;

    try {
        receivedMessages = submit.get(3, TimeUnit.SECONDS);

    } catch (InterruptedException | ExecutionException | TimeoutException e) {
        throw new TimeoutException("Timed out waiting for messages");

    } finally {
        singleThread.shutdown();
        javaConsumerConnector.shutdown();
    }

    return receivedMessages;
}

From source file:no.ntnu.idi.socialhitchhiking.utility.ShareOnFacebook.java

/**
 * Post message with ride information and a link to google maps with info about the route.
 * //from  w  ww  .  j  ava 2s. c o m
 * @param message
 */
@SuppressWarnings("deprecation")
public void postToWall(String message) {

    final Bundle postParams = new Bundle();

    postParams.putString("message", message);
    postParams.putString("caption", "https://maps.google.com/maps?saddr=" + currentRoute.getStartAddress()
            + "&daddr=" + currentRoute.getEndAddress());
    postParams.putString("description", "Click to see the route");

    JSONObject jsonObject = new JSONObject();
    try {
        if (getApp().getSelectedJourney().getVisibility().equals(Visibility.PUBLIC)) {
            jsonObject.put("value", "EVERYONE");
        } else {
            if (getApp().getSelectedJourney().getVisibility().equals(Visibility.FRIENDS_OF_FRIENDS))
                jsonObject.put("value", "FRIENDS_OF_FRIENDS");
            else
                jsonObject.put("value", "ALL_FRIENDS");
        }
    } catch (JSONException e1) {
        // TODO Auto-generated catch block
        e1.printStackTrace();
    }
    postParams.putString("privacy", jsonObject.toString());
    //      postParams.putString("privacy", "EVERYONE");
    //      postParams.putString("actions", "[{'name':'Test a simple Graph API call!','link':'https://developers.facebook.com/tools/explorer?method=GET&path=me'}]");
    postParams.putString("type", "photo");
    postParams.putString("link", "https://maps.google.com/maps?saddr=" + currentRoute.getStartAddress()
            + "&daddr=" + currentRoute.getEndAddress());
    postParams.putString("picture", "http://www.veryicon.com/icon/png/Business/Business/Cars.png");
    //Fix
    ExecutorService executor = Executors.newSingleThreadExecutor();

    Callable<Boolean> callable = new Callable<Boolean>() {
        @Override
        public Boolean call() throws ClientProtocolException, IOException {
            try {
                facebook.request("me");
                String response = facebook.request("me/feed", postParams, "POST");
                Log.d("Tests", "got response: " + response);
                if (response == null || response.equals("") || response.equals("false")) {
                    //showToast("Blank response.");
                } else {
                    //showToast("Trip created and posted to your facebook wall!");
                }
                finish();
            } catch (Exception e) {
                //showToast("Failed to post to wall!");

                e.printStackTrace();
                return false;
                //finish();
            }
            return true;
        }
    };
    Future<Boolean> future = executor.submit(callable);
    try {
        Boolean ret = future.get();
        if (ret) {
            if (isDriver) {
                showToast("Trip created and posted to Facebook!");
            } else {
                showToast("Posted to Facebook!");
            }
        } else {
            showToast("Failed to post to wall!");
        }
    } catch (InterruptedException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (ExecutionException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    executor.shutdown();

}

From source file:com.mirth.connect.connectors.tcp.TcpReceiver.java

@Override
public void onStart() throws ConnectorTaskException {
    disposing.set(false);//ww w.  j a  v  a  2s .  c om
    results.clear();
    clientReaders.clear();

    if (connectorProperties.isServerMode()) {
        // If we're in server mode, use the max connections property to initialize the thread pool
        executor = new ThreadPoolExecutor(0, maxConnections, 60L, TimeUnit.SECONDS,
                new SynchronousQueue<Runnable>());
    } else {
        // If we're in client mode, only a single thread is needed
        executor = Executors.newSingleThreadExecutor();
    }

    if (connectorProperties.isServerMode()) {
        try {
            createServerSocket();
        } catch (IOException e) {
            throw new ConnectorTaskException("Failed to create server socket (" + connectorProperties.getName()
                    + " \"Source\" on channel " + getChannelId() + ").", e);
        }
    }

    // Create the acceptor thread
    thread = new Thread(
            "TCP Receiver Server Acceptor Thread on " + getChannel().getName() + " (" + getChannelId() + ")") {
        @Override
        public void run() {
            while (getCurrentState() == DeployedState.STARTED) {
                Socket socket = null;

                if (connectorProperties.isServerMode()) {
                    // Server mode; wait to accept a client socket on the ServerSocket
                    try {
                        logger.debug("Waiting for new client socket (" + connectorProperties.getName()
                                + " \"Source\" on channel " + getChannelId() + ").");
                        socket = serverSocket.accept();
                        logger.trace("Accepted new socket: " + socket.getRemoteSocketAddress().toString()
                                + " -> " + socket.getLocalSocketAddress());
                    } catch (java.io.InterruptedIOException e) {
                        logger.debug("Interruption during server socket accept operation ("
                                + connectorProperties.getName() + " \"Source\" on channel " + getChannelId()
                                + ").", e);
                    } catch (Exception e) {
                        logger.debug("Error accepting new socket (" + connectorProperties.getName()
                                + " \"Source\" on channel " + getChannelId() + ").", e);
                    }
                } else {
                    // Client mode, manually initiate a client socket
                    try {
                        logger.debug("Initiating for new client socket (" + connectorProperties.getName()
                                + " \"Source\" on channel " + getChannelId() + ").");
                        if (connectorProperties.isOverrideLocalBinding()) {
                            socket = SocketUtil.createSocket(configuration, getLocalAddress(), getLocalPort());
                        } else {
                            socket = SocketUtil.createSocket(configuration);
                        }
                        clientSocket = socket;
                        SocketUtil.connectSocket(socket, getRemoteAddress(), getRemotePort(), timeout);
                    } catch (Exception e) {
                        logger.error("Error initiating new socket (" + connectorProperties.getName()
                                + " \"Source\" on channel " + getChannelId() + ").", e);
                        closeSocketQuietly(socket);
                        socket = null;
                        clientSocket = null;
                    }
                }

                try {
                    ThreadUtils.checkInterruptedStatus();

                    if (socket != null) {
                        synchronized (clientReaders) {
                            TcpReader reader = null;

                            try {
                                // Only allow worker threads to be submitted if we're not currently trying to stop the connector
                                if (disposing.get()) {
                                    return;
                                }
                                reader = new TcpReader(socket);
                                clientReaders.add(reader);
                                results.add(executor.submit(reader));
                            } catch (RejectedExecutionException | SocketException e) {
                                if (e instanceof RejectedExecutionException) {
                                    logger.debug("Executor rejected new task (" + connectorProperties.getName()
                                            + " \"Source\" on channel " + getChannelId() + ").", e);
                                } else {
                                    logger.debug("Error initializing socket (" + connectorProperties.getName()
                                            + " \"Source\" on channel " + getChannelId() + ").", e);
                                }
                                clientReaders.remove(reader);
                                closeSocketQuietly(socket);
                            }
                        }
                    }

                    if (connectorProperties.isServerMode()) {
                        // Remove any completed tasks from the list, but don't try to retrieve currently running tasks
                        cleanup(false, false, true);
                    } else {
                        // Wait until the TcpReader is done
                        cleanup(true, false, true);

                        String info = "Client socket finished, waiting "
                                + connectorProperties.getReconnectInterval() + " ms...";
                        eventController.dispatchEvent(new ConnectionStatusEvent(getChannelId(), getMetaDataId(),
                                getSourceName(), ConnectionStatusEventType.INFO, info));

                        // Use the reconnect interval to determine how long to wait until creating another socket
                        sleep(reconnectInterval);
                    }
                } catch (InterruptedException e) {
                    return;
                }
            }
        }
    };
    thread.start();
}

From source file:models.Search.java

/**
 * @param request The clients request//  ww w .  j  a  v  a  2s  . co m
 * @param serialization The wanted serialization of the returned data.
 * @return the chunks of the elasticsearch scroll scan query
 */
public Chunks<String> executeScrollScan(final Request request, final Serialization serialization) {
    validateSearchParameters();
    return new StringChunks() {
        @Override
        public void onReady(Chunks.Out<String> out) {
            setMessageOut(out);
            ExecutorService executorService = Executors.newSingleThreadExecutor();
            executorService.execute(new Runnable() {
                @Override
                public void run() {
                    doingScrollScanNow = true;
                    bulk(request, serialization);
                }
            });
            executorService.shutdown();
        }
    };
}

From source file:hivemall.mix.server.MixServerTest.java

@Test
public void test2ClientsZeroOneSparseModelWithMixCanceling() throws InterruptedException {
    final int port = NetUtils.getAvailablePort();
    CommandLine cl = CommandLineUtils.parseOptions(
            new String[] { "-port", Integer.toString(port), "-sync_threshold", "30" }, MixServer.getOptions());
    MixServer server = new MixServer(cl);
    ExecutorService serverExec = Executors.newSingleThreadExecutor();
    serverExec.submit(server);//from   www  .j  a  va 2s .  com

    waitForState(server, ServerState.RUNNING);

    final ExecutorService clientsExec = Executors.newCachedThreadPool();
    for (int i = 0; i < 2; i++) {
        clientsExec.submit(new Runnable() {
            @Override
            public void run() {
                try {
                    invokeClient01("test2ClientsZeroOne", port, false, true);
                } catch (InterruptedException e) {
                    Assert.fail(e.getMessage());
                }
            }
        });
    }
    clientsExec.awaitTermination(30, TimeUnit.SECONDS);
    clientsExec.shutdown();
    serverExec.shutdown();
}

From source file:com.heliosdecompiler.helios.gui.view.editors.DisassemblerView.java

private Task<StyleSpans<Collection<String>>> computeHighlightingAsync(CodeArea codeArea) {
    String text = codeArea.getText();
    Task<StyleSpans<Collection<String>>> task = new Task<StyleSpans<Collection<String>>>() {
        @Override/*from  ww  w . j a  v  a 2  s.c  om*/
        protected StyleSpans<Collection<String>> call() throws Exception {
            return computeHighlighting(text);
        }
    };
    Executors.newSingleThreadExecutor().execute(task);
    return task;
}

From source file:com.ec.android.module.bluetooth40.base.BaseBluetoothControlWithProtocolActivity.java

private void initFuture() {
    //?//from   w w w  . ja  va 2 s.com
    ExecutorService mSingleExecutorService = Executors.newSingleThreadExecutor();

    mListeningExecutorService = MoreExecutors.listeningDecorator(mSingleExecutorService);
}

From source file:com.scooter1556.sms.server.service.ScannerService.java

public synchronized void startDeepScan(final List<VideoStream> streams) {
    // Check if media is already being scanned
    if (isScanning() || isDeepScanning()) {
        return;/*from   w  w w  . j a v  a2  s . c  o m*/
    }

    // Create log file
    Timestamp scanTime = new Timestamp(new Date().getTime());
    deepScanLog = SettingsService.getInstance().getLogDirectory() + "/deepscan-" + scanTime + ".log";

    // Reset counter
    dTotal = 0;

    // Create media scanning threads
    deepScanExecutor = Executors.newSingleThreadExecutor();

    deepScanExecutor.submit(new Runnable() {
        @Override
        public void run() {
            LogUtils.writeToLog(deepScanLog, "Found " + streams.size() + " streams to parse.", Level.DEBUG);

            for (VideoStream stream : streams) {
                dTotal++;

                LogUtils.writeToLog(deepScanLog, "Scanning stream " + stream.getStreamId()
                        + " for media element with id " + stream.getMediaElementId(), Level.DEBUG);

                VideoStream update = frameParser.parse(stream);

                if (update != null) {
                    mediaDao.updateVideoStream(update);
                    LogUtils.writeToLog(deepScanLog, stream.toString(), Level.DEBUG);
                }

                LogUtils.writeToLog(deepScanLog, "Finished Scanning stream " + stream.getStreamId()
                        + " for media element with id " + stream.getMediaElementId(), Level.DEBUG);
            }
        }
    });

    deepScanExecutor.shutdownNow();
}

From source file:com.opengamma.web.server.AggregatedViewDefinitionManager.java

private UniqueId aggregatePortfolio(UniqueId basePortfolioId, List<String> aggregatorNames) {
    // REVIEW jonathan 2011-11-13 -- portfolio aggregation is currently painful. The positions obtained from the
    // position source during the orginal portfolio lookup contain munged identifiers that do not correspond to
    // anything in the position master. We end up rewriting the positions even though there is no need, then we cannot
    // clean them up when the portfolio is no longer required in case other portfolios have now referenced the new
    // positions.
    Portfolio basePortfolio = _positionSource.getPortfolio(basePortfolioId, VersionCorrection.LATEST);
    Portfolio resolvedPortfolio = PortfolioCompiler.resolvePortfolio(basePortfolio,
            Executors.newSingleThreadExecutor(), _securitySource);
    List<AggregationFunction<?>> aggregationFunctions = Lists.newArrayListWithCapacity(aggregatorNames.size());
    for (String aggregatorName : aggregatorNames) {
        AggregationFunction<?> aggregationFunction = _portfolioAggregators.get(aggregatorName);
        if (aggregationFunction == null) {
            throw new OpenGammaRuntimeException("Unknown aggregator '" + aggregatorName + "'");
        }/*  w ww. j ava  2  s. c  om*/
        aggregationFunctions.add(aggregationFunction);
    }
    PortfolioAggregator aggregator = new PortfolioAggregator(aggregationFunctions);
    Portfolio aggregatedPortfolio = aggregator.aggregate(resolvedPortfolio);
    return _portfolioSaver.savePortfolio(aggregatedPortfolio, false);
}

From source file:com.streamsets.pipeline.stage.origin.kafka.TestKafkaSource.java

@Test
public void testProduceStringRecords() throws StageException, InterruptedException {

    CountDownLatch startLatch = new CountDownLatch(1);

    ExecutorService executorService = Executors.newSingleThreadExecutor();
    executorService.submit(new ProducerRunnable(TOPIC1, SINGLE_PARTITION, producer, startLatch, DataType.TEXT,
            null, -1, null));/*from   w  ww. jav a 2  s .  c o m*/

    KafkaConfigBean conf = new KafkaConfigBean();
    conf.metadataBrokerList = sdcKafkaTestUtil.getMetadataBrokerURI();
    conf.topic = TOPIC1;
    conf.consumerGroup = CONSUMER_GROUP;
    conf.zookeeperConnect = zkConnect;
    conf.maxBatchSize = 9;
    conf.maxWaitTime = 5000;
    conf.kafkaConsumerConfigs = null;
    conf.produceSingleRecordPerMessage = false;
    conf.dataFormat = DataFormat.TEXT;
    conf.dataFormatConfig.charset = "UTF-8";
    conf.dataFormatConfig.removeCtrlChars = false;
    conf.dataFormatConfig.textMaxLineLen = 4096;

    SourceRunner sourceRunner = new SourceRunner.Builder(StandaloneKafkaSource.class, createSource(conf))
            .addOutputLane("lane").build();
    sourceRunner.runInit();

    startLatch.countDown();

    List<Record> records = new ArrayList<>();
    StageRunner.Output output = getOutputAndRecords(sourceRunner, 5, "lane", records);

    String newOffset = output.getNewOffset();
    Assert.assertNull(newOffset);

    shutDownExecutorService(executorService);
    Assert.assertEquals(5, records.size());

    for (int i = 0; i < records.size(); i++) {
        Assert.assertNotNull(records.get(i).get("/text"));
        Assert.assertTrue(!records.get(i).get("/text").getValueAsString().isEmpty());
        Assert.assertEquals(sdcKafkaTestUtil.generateTestData(DataType.TEXT, null),
                records.get(i).get("/text").getValueAsString());
    }

    sourceRunner.runDestroy();
}