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:io.siddhi.extension.io.file.FileSourceTextFullModeTestCase.java

@Test
public void siddhiIoFileTest4() throws InterruptedException {
    log.info("test SiddhiIoFile [mode = text.full] 4");
    String streams = "" + "@App:name('TestSiddhiApp')" + "@source(type='file', mode='text.full',"
            + "dir.uri='file:/" + dirUri + "/text_full_single', " + "action.after.process='delete', "
            + "@map(type='json'))" + "define stream FooStream (symbol string, price float, volume long); "
            + "define stream BarStream (symbol string, price float, volume long); ";

    String query = "" + "from FooStream " + "select * " + "insert into BarStream; ";

    SiddhiManager siddhiManager = new SiddhiManager();
    SiddhiAppRuntime siddhiAppRuntime = siddhiManager.createSiddhiAppRuntime(streams + query);

    siddhiAppRuntime.addCallback("BarStream", new StreamCallback() {

        @Override//from   w  ww  . ja  va2s  .c om
        public void receive(Event[] events) {
            EventPrinter.print(events);
            int n = count.incrementAndGet();
            for (Event event : events) {
                switch (n) {
                case 1:
                    AssertJUnit.assertEquals("apache", event.getData(0));
                    break;
                case 2:
                    AssertJUnit.assertEquals("google", event.getData(0));
                    break;
                default:
                    AssertJUnit.fail("More events received than expected.");
                }
            }
        }
    });

    Thread t1 = new Thread(new Runnable() {
        @Override
        public void run() {
            siddhiAppRuntime.start();
        }
    });
    ExecutorService executorService = Executors.newSingleThreadExecutor();
    executorService.execute(t1);

    SiddhiTestHelper.waitForEvents(waitTime, 1, count, timeout);

    Thread t2 = new Thread(new Runnable() {
        @Override
        public void run() {
            File source = new File(dirUri + "/text_full/google.json");
            File dest = new File(dirUri + "/text_full_single/google.json");
            while (true) {
                if (count.intValue() == 1) {
                    try {
                        FileUtils.copyFile(source, dest);
                        break;
                    } catch (IOException e) {
                        AssertJUnit.fail(
                                "Failed to add a new file to directory '" + dirUri + "/text_full_single'.");
                    }
                }
            }
        }
    });

    executorService.execute(t2);

    SiddhiTestHelper.waitForEvents(waitTime, 2, count, timeout);

    executorService.shutdown();

    File file = new File(dirUri + "/text_full_single");
    AssertJUnit.assertEquals(0, file.list().length);

    //assert event count
    AssertJUnit.assertEquals("Number of events", 2, count.get());
    siddhiAppRuntime.shutdown();
}

From source file:com.concentricsky.android.khanacademy.app.VideoListActivity.java

@Override
protected void onStart() {
    Log.d(LOG_TAG, "onStart");
    super.onStart();
    stopped = false;// www  .java2 s . c  o m

    mainMenuDelegate = new MainMenuDelegate(this);

    listView = (AbsListView) findViewById(android.R.id.list);
    listView.setOnItemClickListener(clickListener);

    if (listView instanceof ListView) {
        // It is important that this is inflated with listView passed as the parent, despite the attach false parameter.
        // Otherwise, the view ends up with incorrect LayoutParams and we see crazy, crazy behavior.
        headerView = getLayoutInflater().inflate(R.layout.header_video_list, listView, false);
        ListView lv = (ListView) listView;
        if (lv.getHeaderViewsCount() == 0) {
            lv.addHeaderView(headerView);
        }
    } else { // GridView, fixed header
        headerView = findViewById(R.id.header_video_list);
    }

    /**  Responsive layout stuff 
     * 
     *  Based on screen width, we will find either
     *   narrow
     *     a listview with a header view
     *     items are a thumbnail to the left and a title on white space to the right.
     *     header is a thumbnail with overlaid title across the bottom
     * 
     *   middle
     *     a fixed header on top and a grid view below
     *     header is thumb to left, title above scrolling description to right
     *     items are thumbs with title overlaid across the bottom (3 across)
     *   
     *   wide
     *     a fixed header to the left and a grid view on the right
     *     header is thumb on top, title next, description at bottom
     *     items are thumbs with title overlaid across the bottom (3 across)
     *  
     *  
     *  So in this class, we 
     *    find view by id 'list'
     *    if it's a ListView, inflate and attach header view
     *    if not, then the header is fixed and already in the layout
     *    either way, now we can find header views by id
     *    adapter is the same either way
     *  
     *  
     *  
     *  **/

    ActionBar ab = getActionBar();
    displayOptionsAdapter = new ArrayAdapter<String>(getActionBar().getThemedContext(),
            android.R.layout.simple_list_item_1, displayOptions);
    ab.setDisplayHomeAsUpEnabled(true);
    ab.setTitle("");
    ab.setNavigationMode(ActionBar.NAVIGATION_MODE_LIST);
    ab.setListNavigationCallbacks(displayOptionsAdapter, navListener);
    ab.setSelectedNavigationItem(isShowingDownloadedVideosOnly ? 1 : 0);

    requestDataService(new ObjectCallback<KADataService>() {
        @Override
        public void call(KADataService dataService) {
            VideoListActivity.this.dataService = dataService;

            if (topicId != null) {
                Dao<Topic, String> topicDao;
                try {
                    topicDao = dataService.getHelper().getTopicDao();
                    topic = topicDao.queryForId(topicId);
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            } else {
                Log.e(LOG_TAG, "Topic id not set for video list");
                topic = dataService.getRootTopic();
                topicId = topic.getId();
            }

            thumbnailManager = dataService.getThumbnailManager();
            api = dataService.getAPIAdapter();
            api.registerUserUpdateListener(userUpdateListener);

            // This instead happens in ActionBar.OnNavigationListener#onNavigationItemSelected, which
            // fires after onResume.
            //            setParentTopic(topic);
        }
    });

    IntentFilter filter = new IntentFilter();
    filter.addAction(ACTION_LIBRARY_UPDATE);
    filter.addAction(ACTION_BADGE_EARNED);
    filter.addAction(ACTION_OFFLINE_VIDEO_SET_CHANGED);
    filter.addAction(ACTION_DOWNLOAD_PROGRESS_UPDATE);
    filter.addAction(ACTION_TOAST);
    LocalBroadcastManager.getInstance(this).registerReceiver(receiver, filter);
    thumbExecutor = Executors.newSingleThreadExecutor();
}

From source file:com.ngdata.hbaseindexer.master.IndexerMaster.java

private void startFullIndexBuild(final String indexerName) {
    try {//from  ww w .  j  a  v a2s.com
        String lock = indexerModel.lockIndexer(indexerName);
        try {
            // Read current situation of record and assure it is still actual
            final IndexerDefinition indexer = indexerModel.getFreshIndexer(indexerName);
            IndexerDefinitionBuilder updatedIndexer = new IndexerDefinitionBuilder().startFrom(indexer);
            final String[] batchArguments = createBatchArguments(indexer);
            if (needsBatchBuildStart(indexer)) {
                final ListeningExecutorService executor = MoreExecutors
                        .listeningDecorator(Executors.newSingleThreadExecutor());
                ListenableFuture<Integer> future = executor.submit(new Callable<Integer>() {
                    @Override
                    public Integer call() throws Exception {
                        HBaseMapReduceIndexerTool tool = new HBaseMapReduceIndexerTool();
                        tool.setConf(hbaseConf);
                        return tool.run(batchArguments,
                                new IndexerDefinitionUpdaterJobProgressCallback(indexerName));
                    }
                });

                Futures.addCallback(future, new FutureCallback<Integer>() {
                    @Override
                    public void onSuccess(Integer exitCode) {
                        markBatchBuildCompleted(indexerName, exitCode == 0);
                        executor.shutdownNow();
                    }

                    @Override
                    public void onFailure(Throwable throwable) {
                        log.error("batch index build failed", throwable);
                        markBatchBuildCompleted(indexerName, false);
                        executor.shutdownNow();
                    }
                });

                BatchBuildInfo jobInfo = new BatchBuildInfo(System.currentTimeMillis(), null, null,
                        batchArguments);
                updatedIndexer.activeBatchBuildInfo(jobInfo).batchIndexingState(BatchIndexingState.BUILDING)
                        .batchIndexCliArguments(null).build();

                indexerModel.updateIndexerInternal(updatedIndexer.build());

                log.info("Started batch index build for index " + indexerName);

            }
        } finally {
            indexerModel.unlockIndexer(lock);
        }
    } catch (Throwable t) {
        log.error("Error trying to start index build job for index " + indexerName, t);
    }
}

From source file:com.googlecode.concurrentlinkedhashmap.MultiThreadedTest.java

private void executeWithTimeOut(ConcurrentLinkedHashMap<?, ?> map, Callable<Long> task) {
    ExecutorService es = Executors.newSingleThreadExecutor();
    Future<Long> future = es.submit(task);
    try {/*from  w  ww  .  ja  va  2s .  co  m*/
        long timeNS = future.get(timeOut, SECONDS);
        debug("\nExecuted in %d second(s)", NANOSECONDS.toSeconds(timeNS));
        assertThat(map, is(valid()));
    } catch (ExecutionException e) {
        fail("Exception during test: " + e.toString(), e);
    } catch (TimeoutException e) {
        handleTimout(map, es, e);
    } catch (InterruptedException e) {
        fail("", e);
    }
}

From source file:com.properned.application.SystemController.java

public void openPropertiesFile() {
    logger.info("Open the 'Open file' dialog");
    FileChooser fileChooser = new FileChooser();
    fileChooser.setTitle(MessageReader.getInstance().getMessage("window.openFile.title"));
    String lastPathUsed = Preferences.getInstance().getLastPathUsed();
    File lastSelectedFile = new File(lastPathUsed);
    if (StringUtils.isNotEmpty(lastPathUsed) && lastSelectedFile != null
            && lastSelectedFile.getParentFile() != null && lastSelectedFile.getParentFile().exists()) {
        fileChooser.setInitialDirectory(lastSelectedFile.getParentFile());
    }/*ww w.  ja  v  a  2s  .c  o m*/
    File selectedFile = fileChooser
            .showOpenDialog(Properned.getInstance().getPrimaryStage().getScene().getWindow());
    if (selectedFile != null) {
        logger.info("Selected file : " + selectedFile.getAbsolutePath());
        Task<Void> loadTask = new Task<Void>() {
            @Override
            protected Void call() throws Exception {
                loadFileList(selectedFile);
                return null;
            }
        };

        Executors.newSingleThreadExecutor().submit(loadTask);
    }
}

From source file:com.netflix.curator.framework.recipes.cache.TestPathChildrenCache.java

@Test
public void testRebuildAgainstOtherProcesses() throws Exception {
    final CuratorFramework client = CuratorFrameworkFactory.newClient(server.getConnectString(),
            new RetryOneTime(1));
    client.start();/*from  w ww.  j  a  v  a  2  s.  c  o  m*/
    try {
        client.create().forPath("/test");
        client.create().forPath("/test/foo");
        client.create().forPath("/test/bar");
        client.create().forPath("/test/snafu", "original".getBytes());

        final CountDownLatch addedLatch = new CountDownLatch(2);
        final PathChildrenCache cache = new PathChildrenCache(client, "/test", true);
        cache.getListenable().addListener(new PathChildrenCacheListener() {
            @Override
            public void childEvent(CuratorFramework client, PathChildrenCacheEvent event) throws Exception {
                if (event.getType() == PathChildrenCacheEvent.Type.CHILD_ADDED) {
                    if (event.getData().getPath().equals("/test/test")) {
                        addedLatch.countDown();
                    }
                } else if (event.getType() == PathChildrenCacheEvent.Type.CHILD_UPDATED) {
                    if (event.getData().getPath().equals("/test/snafu")) {
                        addedLatch.countDown();
                    }
                }
            }
        });
        cache.rebuildTestExchanger = new Exchanger<Object>();
        ExecutorService service = Executors.newSingleThreadExecutor();
        final AtomicReference<String> deletedPath = new AtomicReference<String>();
        Future<Object> future = service.submit(new Callable<Object>() {
            @Override
            public Object call() throws Exception {
                cache.rebuildTestExchanger.exchange(new Object());

                // simulate another process adding a node while we're rebuilding
                client.create().forPath("/test/test");

                List<ChildData> currentData = cache.getCurrentData();
                Assert.assertTrue(currentData.size() > 0);

                // simulate another process removing a node while we're rebuilding
                client.delete().forPath(currentData.get(0).getPath());
                deletedPath.set(currentData.get(0).getPath());

                cache.rebuildTestExchanger.exchange(new Object());

                ChildData childData = null;
                while (childData == null) {
                    childData = cache.getCurrentData("/test/snafu");
                    Thread.sleep(1000);
                }
                Assert.assertEquals(childData.getData(), "original".getBytes());
                client.setData().forPath("/test/snafu", "grilled".getBytes());

                cache.rebuildTestExchanger.exchange(new Object());

                return null;
            }
        });
        cache.start(PathChildrenCache.StartMode.BUILD_INITIAL_CACHE);
        future.get();

        Assert.assertTrue(addedLatch.await(10, TimeUnit.SECONDS));
        Assert.assertNotNull(cache.getCurrentData("/test/test"));
        Assert.assertNull(cache.getCurrentData(deletedPath.get()));
        Assert.assertEquals(cache.getCurrentData("/test/snafu").getData(), "grilled".getBytes());

        cache.close();
    } finally {
        client.close();
    }
}

From source file:com.github.kubernetes.java.client.live.KubernetesApiClientLiveTest.java

@Test
public void testCreateReplicationController() throws Exception {
    if (log.isDebugEnabled()) {
        log.debug("Creating a Replication Controller: " + contr);
    }/*from w  ww .  j av a2  s .  c  om*/
    getClient().createReplicationController(contr);
    assertNotNull(getClient().getReplicationController(contr.getId()));

    ExecutorService executor = Executors.newSingleThreadExecutor();
    Future<PodList> future = executor.submit(new Callable<PodList>() {
        public PodList call() throws Exception {
            PodList pods;
            do {
                log.info("Waiting for Pods to be ready");
                Thread.sleep(1000);
                pods = getClient()
                        .getSelectedPods(ImmutableMap.of("name", "kubernetes-test-controller-selector"));
                if (pods.isEmpty()) {
                    continue;
                }

                StateInfo info = pods.get(0).getCurrentState().getInfo("kubernetes-test");
                if ((info != null) && info.getState("waiting") != null) {
                    throw new RuntimeException("Pod is waiting due to " + info.getState("waiting"));
                }
            } while (pods.isEmpty() || !FluentIterable.from(pods).allMatch(new Predicate<Pod>() {
                public boolean apply(Pod pod) {
                    return "Running".equals(pod.getCurrentState().getStatus());
                }
            }));
            return pods;
        }
    });

    PodList pods;
    try {
        pods = future.get(90, TimeUnit.SECONDS);
    } finally {
        executor.shutdownNow();
    }
    for (Pod pod : pods) {
        assertNotNull(pod.getCurrentState().getInfo("kubernetes-test").getState("running"));
        assertNotNull(pod.getCurrentState().getNetInfo().getState("running"));
    }

    // test recreation using same id
    try {
        getClient().createReplicationController(contr);
        fail("Should have thrown exception");
    } catch (Exception e) {
        // ignore
    }
    assertNotNull(getClient().getReplicationController(contr.getId()));

    PodList podList = getClient().getSelectedPods(contr.getLabels());
    assertNotNull(podList);
    assertNotNull(podList.getItems());
    assertEquals(contr.getDesiredState().getReplicas(), podList.getItems().size());
}

From source file:com.adaptris.jdbc.connection.FailoverDatasourceTest.java

@Test
public void testAbort() throws Exception {
    Connection conn = new MyProxy();

    try {//from w w w  . j a va 2 s.c o  m
        try {
            conn.abort(Executors.newSingleThreadExecutor());
        } catch (SQLException e) {

        }
    } finally {
        JdbcUtil.closeQuietly(conn);
    }
}

From source file:maltcms.ui.nb.pipelineRunner.ui.PipelineRunnerTopComponent.java

private void runButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_runButtonActionPerformed
    final MaltcmsLocalHostExecution mlhe = getActiveProcess();
    if (mlhe != null) {
        final Future<File> f = MaltcmsLocalHostExecution.createAndRun(mlhe.getConfigurationFile().getName(),
                mlhe);/*w ww  .  jav a 2 s. c o  m*/
        setProcessRunning(mlhe);
        final ExecutorService es = Executors.newSingleThreadExecutor();
        Runnable r = new Runnable() {

            @Override
            public void run() {
                final File result;
                try {
                    result = f.get();
                    if (result != null) {
                        Runnable resultImporter = new Runnable() {
                            @Override
                            public void run() {
                                Collection<? extends IFileResultFinder> resultFinders = Lookup.getDefault()
                                        .lookupAll(IFileResultFinder.class);
                                Collection<IFileBasedToolResultDescriptor> c = new ArrayList<>();
                                for (IFileResultFinder f : resultFinders) {
                                    Logger.getLogger(PipelineRunnerTopComponent.class.getName()).log(Level.INFO,
                                            "Invoking fileResultFinder {0}", f.getClass().getName());
                                    if (f.getResults(result.getParentFile()).length > 0) {
                                        c.add(f.createDescriptor((IChromAUIProject) mlhe.getProject(),
                                                result.getParentFile()));
                                    } else {
                                        Logger.getLogger(PipelineRunnerTopComponent.class.getName()).log(
                                                Level.INFO,
                                                "Skipping fileResultFinder {0}, no suitable results!",
                                                f.getClass().getName());
                                    }
                                }
                                Logger.getLogger(PipelineRunnerTopComponent.class.getName()).log(Level.INFO,
                                        "Showing dialog for {0} descriptors", c.size());
                                Collection<? extends IFileBasedToolResultDescriptor> results = Dialogs
                                        .showAndSelectDescriptors(c, Lookups.fixed(mlhe.getProject()),
                                                IFileBasedToolResultDescriptor.class,
                                                "Select results to import", "Select tools to import results:");
                                for (IFileBasedToolResultDescriptor descr : results) {
                                    AProgressAwareRunnable.createAndRun("Running " + descr.getDisplayName(),
                                            descr.getProgressAwareRunnable());
                                }
                            }
                        };
                        RequestProcessor.getDefault().post(resultImporter);
                        Runnable updater = new Runnable() {

                            @Override
                            public void run() {
                                PipelineRunnerTopComponent.findInstance().removeProcess(mlhe);
                            }
                        };
                        SwingUtilities.invokeLater(updater);
                    }
                } catch (InterruptedException | ExecutionException ex) {
                    Exceptions.printStackTrace(ex);
                }
            }
        };
        es.submit(r);
        es.shutdown();
    }
    //        Logger.getLogger(PipelineRunnerTopComponent.class.getName()).info("Configuration: " + ConfigurationUtils.toString(cfg));
    //        if (lhmp != null) {
    //            if (!lhmp.isDone()) {
    //                Logger.getLogger(PipelineRunnerTopComponent.class.getName()).warning("Maltcms is already running! Please stop the running process, before restarting!");
    //                return;
    //            }
    //        }
    //
    //        try {
    //            Factory f = Factory.getInstance();
    //            f.configure(buildCompositeConfiguration(new PropertiesConfiguration(this.cfg)));
    //            ICommandSequence ics = f.createCommandSequence();
    //            for (IFragmentCommand afc : ics.getCommands()) {
    //                System.out.println("Executing command: " + afc.getClass().getName());
    //            }
    //            while (ics.hasNext()) {
    //                ics.next();
    //            }
    //            f.shutdown();
    //            try {
    //                Factory.awaitTermination(1, TimeUnit.DAYS);
    //            } catch (InterruptedException ex) {
    //                Exceptions.printStackTrace(ex);
    //            }
    //            // Save configuration
    //            Factory.dumpConfig("runtime.properties", ics.getIWorkflow().getStartupDate());
    //            // Save workflow
    //            final IWorkflow iw = ics.getIWorkflow();
    //            iw.save();
    //
    //        } catch (ConfigurationException ex) {
    //            Exceptions.printStackTrace(ex);
    //        }
    //        LocalHostLauncher lhh;
    //        try {
    //            lhh = new LocalHostLauncher(buildCompositeConfiguration(new PropertiesConfiguration(this.cfg)), this.jPanel1, false);
    //            lhmp = lhh.getProcess();
    //            ExecutorService es = Executors.newSingleThreadExecutor();
    //            es.execute(lhh);
    ////        submit();
    //            jButton1.setEnabled(false);
    //            jButton2.setEnabled(true);
    //        } catch (ConfigurationException ex) {
    //            Exceptions.printStackTrace(ex);
    //        }
}

From source file:com.isoftstone.crawl.template.crawlstate.CrawlState.java

/**
 * ?.// w w w .jav  a  2s  .co m
 *
 * @param folderNameSeed
 */
public String reParse(String folderNameSeed, boolean isDeploy, boolean isNomal) {
    String nutch_reparse;
    String solrURL = Config.getValue(WebtoolConstants.KEY_NUTCH_SOLR_URL);
    String crawlDir = Config.getValue(WebtoolConstants.KEY_NUTCH_CRAWLDIR);
    String folderNameData = folderNameSeed.substring(0, folderNameSeed.lastIndexOf("_"));

    //-- ???.
    if (isDeploy) {
        nutch_reparse = Config.getValue(WebtoolConstants.KEY_NUTCH_REPARSE_DEPLOY);
    } else {
        nutch_reparse = Config.getValue(WebtoolConstants.KEY_NUTCH_REPARSE_LOCAL);
    }

    //-- data.
    if (!isNomal) {
        folderNameData = folderNameData.substring(0, folderNameData.lastIndexOf("_")) + "_"
                + WebtoolConstants.INCREMENT_FILENAME_SIGN;
    }

    String data_folder = crawlDir + folderNameData + "_data";

    LOG.info("ParseAndIndex: nutch_root: " + nutch_reparse);
    LOG.info("ParseAndIndex: data_folder: " + data_folder);

    String command = "java -jar /reparseAndIndex.jar " + nutch_reparse + " " + data_folder + " " + solrURL
            + " true";
    LOG.info("ParseAndIndex: command:" + command);
    final RunManager runManager = getRunmanager(command);

    String resultMsg = "";
    ExecutorService es = Executors.newSingleThreadExecutor();
    Future<String> result = es.submit(new Callable<String>() {
        public String call() throws Exception {
            // the other thread
            return ShellUtils.execCmd(runManager);
        }
    });
    try {
        resultMsg = result.get();
    } catch (Exception e) {
        // failed
    }

    //ShellUtils.execCmd(runManager);

    return resultMsg;
}