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.realm.RealmTests.java

private boolean runMethodOnWrongThread(final Method method) throws InterruptedException, ExecutionException {
    if (method != Method.METHOD_BEGIN) {
        realm.beginTransaction();//from  w ww .  j a va  2s.  c o  m
        realm.createObject(Dog.class);
    }
    ExecutorService executorService = Executors.newSingleThreadExecutor();
    Future<Boolean> future = executorService.submit(new Callable<Boolean>() {
        @Override
        public Boolean call() throws Exception {
            try {
                switch (method) {
                case METHOD_BEGIN:
                    realm.beginTransaction();
                    break;
                case METHOD_COMMIT:
                    realm.commitTransaction();
                    break;
                case METHOD_CANCEL:
                    realm.cancelTransaction();
                    break;
                case METHOD_DELETE_TYPE:
                    realm.delete(AllTypes.class);
                    break;
                case METHOD_DELETE_ALL:
                    realm.deleteAll();
                    break;
                case METHOD_DISTINCT:
                    realm.distinct(AllTypesPrimaryKey.class, "columnLong");
                    break;
                case METHOD_CREATE_OBJECT:
                    realm.createObject(AllTypes.class);
                    break;
                case METHOD_COPY_TO_REALM:
                    realm.copyToRealm(new AllTypes());
                    break;
                case METHOD_COPY_TO_REALM_OR_UPDATE:
                    realm.copyToRealm(new AllTypesPrimaryKey());
                    break;
                case METHOD_CREATE_ALL_FROM_JSON:
                    realm.createAllFromJson(AllTypes.class, "[{}]");
                    break;
                case METHOD_CREATE_OR_UPDATE_ALL_FROM_JSON:
                    realm.createOrUpdateAllFromJson(AllTypesPrimaryKey.class, "[{\"columnLong\":1}]");
                    break;
                case METHOD_CREATE_FROM_JSON:
                    realm.createObjectFromJson(AllTypes.class, "{}");
                    break;
                case METHOD_CREATE_OR_UPDATE_FROM_JSON:
                    realm.createOrUpdateObjectFromJson(AllTypesPrimaryKey.class, "{\"columnLong\":1}");
                    break;
                }
                return false;
            } catch (IllegalStateException ignored) {
                return true;
            } catch (RealmException jsonFailure) {
                // TODO: Eew. Reconsider how our JSON methods reports failure. See https://github.com/realm/realm-java/issues/1594
                return (jsonFailure.getMessage().equals("Could not map Json"));
            }
        }
    });

    boolean result = future.get();
    if (method != Method.METHOD_BEGIN) {
        realm.cancelTransaction();
    }
    return result;
}

From source file:com.o2d.pkayjava.editor.proxy.ProjectManager.java

public void importAtlasesIntoProject(final Array<FileHandle> files, ProgressHandler progressHandler) {
    handler = progressHandler;/*w ww. j  a v  a2s  .c  om*/
    currentPercent = 0;
    ExecutorService executor = Executors.newSingleThreadExecutor();
    executor.execute(() -> {
        for (FileHandle fileHandle : files) {
            // TODO: logic goes here
        }
    });
    executor.execute(() -> {
        changePercentBy(100 - currentPercent);
        try {
            Thread.sleep(500);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        handler.progressComplete();
    });
    executor.shutdown();
}

From source file:i2p.bote.I2PBote.java

/**
 * Calls {@link #changePassword(byte[], byte[], byte[])} in a new thread and
 * returns a {@link Future} that throws the same exceptions the synchronous
 * variant would./*from www .j a va  2  s. c om*/
 * @param oldPassword
 * @param newPassword
 * @param confirmNewPassword
 */
public void changePasswordAsync(final byte[] oldPassword, final byte[] newPassword,
        final byte[] confirmNewPassword) {
    passwordChangeResult = Executors.newSingleThreadExecutor().submit(new Callable<Void>() {
        @Override
        public Void call() throws IOException, GeneralSecurityException, PasswordException {
            changePassword(oldPassword, newPassword, confirmNewPassword);
            return null;
        }
    });
}

From source file:ddf.catalog.resource.download.ReliableResourceDownloadManagerTest.java

private void startDownload(boolean cacheEnabled, int chunkSize, boolean cacheWhenCanceled, Metacard metacard,
        ResourceRetriever retriever) throws Exception {
    downloadMgr = new ReliableResourceDownloadManager(resourceCache, eventPublisher, eventListener,
            downloadStatusInfo, Executors.newSingleThreadExecutor());
    downloadMgr.setCacheEnabled(cacheEnabled);
    downloadMgr.setChunkSize(chunkSize);
    downloadMgr.setCacheWhenCanceled(cacheWhenCanceled);

    ResourceResponse newResourceResponse = downloadMgr.download(resourceRequest, metacard, retriever);
    assertThat(newResourceResponse, is(notNullValue()));
    productInputStream = newResourceResponse.getResource().getInputStream();
    assertThat(productInputStream, is(instanceOf(ReliableResourceInputStream.class)));
}

From source file:com.o2d.pkayjava.editor.proxy.ProjectManager.java

public void importImagesIntoProject(final Array<FileHandle> files, ProgressHandler progressHandler) {
    if (files == null) {
        return;//ww w.ja  v  a 2s .com
    }
    handler = progressHandler;
    currentPercent = 0;
    ExecutorService executor = Executors.newSingleThreadExecutor();
    executor.execute(() -> {
        copyImageFilesForAllResolutionsIntoProject(files, true);
        ResolutionManager resolutionManager = facade.retrieveProxy(ResolutionManager.NAME);
        resolutionManager.rePackProjectImagesForAllResolutions();
    });
    executor.execute(() -> {
        changePercentBy(100 - currentPercent);
        try {
            Thread.sleep(500);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        handler.progressComplete();
    });
    executor.shutdown();
}

From source file:com.uwsoft.editor.data.manager.DataManager.java

public void importExternalImagesIntoProject(final ArrayList<File> files, ProgressHandler progressHandler) {
    handler = progressHandler;/*from w  ww.j a  v  a2 s.  c  o m*/
    currentPercent = 0;
    ExecutorService executor = Executors.newSingleThreadExecutor();
    executor.execute(new Runnable() {
        @Override
        public void run() {
            copyImageFilesForAllResolutionsIntoProject(files, true);
            resolutionManager.rePackProjectImagesForAllResolutions();
        }
    });
    executor.execute(new Runnable() {
        @Override
        public void run() {
            changePercentBy(100 - currentPercent);
            try {
                Thread.sleep(500);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }

            handler.progressComplete();
        }
    });
    executor.shutdown();
}

From source file:com.datastax.loader.CqlDelimLoad.java

public boolean run(String[] args)
        throws IOException, ParseException, InterruptedException, ExecutionException, KeyStoreException,
        NoSuchAlgorithmException, KeyManagementException, CertificateException, UnrecoverableKeyException {
    if (false == parseArgs(args)) {
        System.err.println("Bad arguments");
        System.err.println(usage());
        return false;
    }//from  w  ww .jav  a 2  s  . c om

    // Setup
    if (false == setup())
        return false;

    // open file
    Deque<File> fileList = new ArrayDeque<File>();
    File infile = null;
    File[] inFileList = null;
    boolean onefile = true;
    if (STDIN.equalsIgnoreCase(filename)) {
        infile = null;
    } else {
        infile = new File(filename);
        if (infile.isFile()) {
        } else {
            inFileList = infile.listFiles();
            if (inFileList.length < 1)
                throw new IOException("directory is empty");
            onefile = false;
            Arrays.sort(inFileList, new Comparator<File>() {
                public int compare(File f1, File f2) {
                    return f1.getName().compareTo(f2.getName());
                }
            });
            for (int i = 0; i < inFileList.length; i++)
                fileList.push(inFileList[i]);
        }
    }

    // Launch Threads
    ExecutorService executor;
    long total = 0;
    if (onefile) {
        // One file/stdin to process
        executor = Executors.newSingleThreadExecutor();
        Callable<Long> worker = new CqlDelimLoadTask(cqlSchema, delimiter, charsPerColumn, nullString,
                commentString, dateFormatString, localDateFormatString, boolStyle, locale, maxErrors, skipRows,
                skipCols, maxRows, badDir, infile, session, consistencyLevel, numFutures, batchSize, numRetries,
                queryTimeout, maxInsertErrors, successDir, failureDir, nullsUnset, format, keyspace, table);
        Future<Long> res = executor.submit(worker);
        total = res.get();
        executor.shutdown();
    } else {
        executor = Executors.newFixedThreadPool(numThreads);
        Set<Future<Long>> results = new HashSet<Future<Long>>();
        while (!fileList.isEmpty()) {
            File tFile = fileList.pop();
            Callable<Long> worker = new CqlDelimLoadTask(cqlSchema, delimiter, charsPerColumn, nullString,
                    commentString, dateFormatString, localDateFormatString, boolStyle, locale, maxErrors,
                    skipRows, skipCols, maxRows, badDir, tFile, session, consistencyLevel, numFutures,
                    batchSize, numRetries, queryTimeout, maxInsertErrors, successDir, failureDir, nullsUnset,
                    format, keyspace, table);
            results.add(executor.submit(worker));
        }
        executor.shutdown();
        for (Future<Long> res : results)
            total += res.get();
    }

    // Cleanup
    cleanup();
    //System.err.println("Total rows inserted: " + total);

    return true;
}

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

@Test
public void testProduceLogRecordsWithStackTraceSameMessage()
        throws StageException, IOException, InterruptedException {

    CountDownLatch startLatch = new CountDownLatch(1);
    ExecutorService executorService = Executors.newSingleThreadExecutor();
    executorService.submit(new ProducerRunnable(TOPIC11, SINGLE_PARTITION, producer, startLatch,
            DataType.LOG_STACK_TRACE, null, -1, null));

    KafkaConfigBean conf = new KafkaConfigBean();
    conf.metadataBrokerList = sdcKafkaTestUtil.getMetadataBrokerURI();
    conf.topic = TOPIC11;// w ww. j  a  v  a  2 s  . co  m
    conf.consumerGroup = CONSUMER_GROUP;
    conf.zookeeperConnect = zkConnect;
    conf.maxBatchSize = 9;
    conf.maxWaitTime = 10000;
    conf.kafkaConsumerConfigs = null;
    conf.produceSingleRecordPerMessage = false;
    conf.dataFormat = DataFormat.LOG;
    conf.dataFormatConfig.charset = "UTF-8";
    conf.dataFormatConfig.removeCtrlChars = false;
    conf.dataFormatConfig.logMode = LogMode.LOG4J;
    conf.dataFormatConfig.logMaxObjectLen = 10000;
    conf.dataFormatConfig.retainOriginalLine = true;
    conf.dataFormatConfig.customLogFormat = null;
    conf.dataFormatConfig.regex = null;
    conf.dataFormatConfig.fieldPathsToGroupName = null;
    conf.dataFormatConfig.grokPatternDefinition = null;
    conf.dataFormatConfig.grokPattern = null;
    conf.dataFormatConfig.onParseError = OnParseError.INCLUDE_AS_STACK_TRACE;
    conf.dataFormatConfig.maxStackTraceLines = 100;
    conf.dataFormatConfig.enableLog4jCustomLogFormat = false;
    conf.dataFormatConfig.log4jCustomLogFormat = null;

    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, 9, "lane", records);

    shutDownExecutorService(executorService);

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

    Assert.assertEquals(9, records.size());

    for (Record record : records) {
        Assert.assertEquals(sdcKafkaTestUtil.generateTestData(DataType.LOG_STACK_TRACE, null),
                record.get().getValueAsMap().get("originalLine").getValueAsString());

        Assert.assertFalse(record.has("/truncated"));

        Assert.assertTrue(record.has("/" + Constants.TIMESTAMP));
        Assert.assertEquals("2015-03-24 17:49:16,808",
                record.get("/" + Constants.TIMESTAMP).getValueAsString());

        Assert.assertTrue(record.has("/" + Constants.SEVERITY));
        Assert.assertEquals("ERROR", record.get("/" + Constants.SEVERITY).getValueAsString());

        Assert.assertTrue(record.has("/" + Constants.CATEGORY));
        Assert.assertEquals("ExceptionToHttpErrorProvider",
                record.get("/" + Constants.CATEGORY).getValueAsString());

        Assert.assertTrue(record.has("/" + Constants.MESSAGE));
        Assert.assertEquals(sdcKafkaTestUtil.ERROR_MSG_WITH_STACK_TRACE,
                record.get("/" + Constants.MESSAGE).getValueAsString());
    }

    sourceRunner.runDestroy();
}

From source file:fr.bmartel.speedtest.SpeedTestTask.java

/**
 * start FTP download with specific port, user, password.
 *
 * @param hostname ftp host/*from  w  w  w . ja v  a 2  s .  com*/
 * @param uri      ftp uri
 * @param user     ftp username
 * @param password ftp password
 */
public void startFtpDownload(final String hostname, final int port, final String uri, final String user,
        final String password) {

    mSpeedTestMode = SpeedTestMode.DOWNLOAD;

    mErrorDispatched = false;
    mForceCloseSocket = false;

    if (mReadExecutorService == null || mReadExecutorService.isShutdown()) {
        mReadExecutorService = Executors.newSingleThreadExecutor();
    }

    mReadExecutorService.execute(new Runnable() {

        @Override
        public void run() {

            final FTPClient ftpclient = new FTPClient();

            try {
                ftpclient.connect(hostname, port);
                ftpclient.login(user, password);
                ftpclient.enterLocalPassiveMode();
                ftpclient.setFileType(FTP.BINARY_FILE_TYPE);

                mDownloadTemporaryPacketSize = 0;

                mTimeStart = System.currentTimeMillis();
                mTimeEnd = 0;

                if (mRepeatWrapper.isFirstDownload()) {
                    mRepeatWrapper.setFirstDownloadRepeat(false);
                    mRepeatWrapper.setStartDate(mTimeStart);
                }

                mDownloadPckSize = new BigDecimal(getFileSize(ftpclient, uri));

                if (mRepeatWrapper.isRepeatDownload()) {
                    mRepeatWrapper.updatePacketSize(mDownloadPckSize);
                }

                mFtpInputstream = ftpclient.retrieveFileStream(uri);

                if (mFtpInputstream != null) {

                    final byte[] bytesArray = new byte[SpeedTestConst.READ_BUFFER_SIZE];

                    int read;
                    while ((read = mFtpInputstream.read(bytesArray)) != -1) {
                        mDownloadTemporaryPacketSize += read;

                        if (mRepeatWrapper.isRepeatDownload()) {
                            mRepeatWrapper.updateTempPacketSize(read);
                        }

                        if (!mReportInterval) {
                            final SpeedTestReport report = mSocketInterface.getLiveDownloadReport();

                            for (int i = 0; i < mListenerList.size(); i++) {
                                mListenerList.get(i).onDownloadProgress(report.getProgressPercent(), report);
                            }
                        }

                        if (mDownloadTemporaryPacketSize == mDownloadPckSize.longValueExact()) {
                            break;
                        }
                    }

                    mFtpInputstream.close();

                    mTimeEnd = System.currentTimeMillis();

                    mReportInterval = false;
                    final SpeedTestReport report = mSocketInterface.getLiveDownloadReport();

                    for (int i = 0; i < mListenerList.size(); i++) {
                        mListenerList.get(i).onDownloadFinished(report);
                    }

                } else {

                    mReportInterval = false;
                    SpeedTestUtils.dispatchError(mForceCloseSocket, mListenerList, true, "cant create stream "
                            + "from uri " + uri + " with reply code : " + ftpclient.getReplyCode());
                }

                if (!mRepeatWrapper.isRepeatDownload()) {
                    closeExecutors();
                }

            } catch (IOException e) {
                //e.printStackTrace();
                mReportInterval = false;
                catchError(true, e.getMessage());
            } finally {
                mErrorDispatched = false;
                mSpeedTestMode = SpeedTestMode.NONE;
                disconnectFtp(ftpclient);
            }
        }
    });
}

From source file:it.unibo.alchemist.language.EnvironmentBuilder.java

private static <T> Future<Result<T>> build(final EnvironmentBuilder<T> builder) {
    final ExecutorService ex = Executors.newSingleThreadExecutor();
    final Future<Result<T>> result = ex.submit(() -> {
        builder.buildEnvironment();//w w w .j  a va2  s  .com
        return Result.build(builder.result, builder.random);
    });
    ex.shutdown();
    return result;
}