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.mobilyzer.MeasurementScheduler.java

@Override
public void onCreate() {
    Logger.d("MeasurementScheduler -> onCreate called");
    PhoneUtils.setGlobalContext(this.getApplicationContext());

    phoneUtils = PhoneUtils.getPhoneUtils();
    phoneUtils.registerSignalStrengthListener();

    this.measurementExecutor = Executors.newSingleThreadExecutor();
    this.mainQueue = new PriorityBlockingQueue<MeasurementTask>(Config.MAX_TASK_QUEUE_SIZE,
            new TaskComparator());
    this.waitingTasksQueue = new PriorityBlockingQueue<MeasurementTask>(Config.MAX_TASK_QUEUE_SIZE,
            new WaitingTasksComparator());
    this.pendingTasks = new ConcurrentHashMap<MeasurementTask, Future<MeasurementResult[]>>();
    this.tasksStatus = new ConcurrentHashMap<String, MeasurementScheduler.TaskStatus>();
    this.alarmManager = (AlarmManager) this.getSystemService(Context.ALARM_SERVICE);
    this.resourceCapManager = new ResourceCapManager(Config.DEFAULT_BATTERY_THRESH_PRECENT, this);

    this.serverTasks = new HashMap<String, Date>();
    // this.currentSchedule = new HashMap<String, MeasurementTask>();

    this.idToClientKey = new ConcurrentHashMap<String, String>();

    messenger = new Messenger(new APIRequestHandler(this));

    gcmManager = new GCMManager(this.getApplicationContext());

    this.setCurrentTask(null);
    this.setCurrentTaskStartTime(null);

    this.checkin = new Checkin(this);
    this.checkinRetryIntervalSec = Config.MIN_CHECKIN_RETRY_INTERVAL_SEC;
    this.checkinRetryCnt = 0;
    this.checkinTask = new CheckinTask();

    this.batteryThreshold = -1;
    this.checkinIntervalSec = -1;
    this.dataUsageProfile = DataUsageProfile.NOTASSIGNED;

    //    loadSchedulerState();//TODO(ASHKAN)

    // Register activity specific BroadcastReceiver here
    IntentFilter filter = new IntentFilter();
    filter.addAction(UpdateIntent.CHECKIN_ACTION);
    filter.addAction(UpdateIntent.CHECKIN_RETRY_ACTION);
    filter.addAction(UpdateIntent.MEASUREMENT_ACTION);
    filter.addAction(UpdateIntent.MEASUREMENT_PROGRESS_UPDATE_ACTION);
    filter.addAction(UpdateIntent.GCM_MEASUREMENT_ACTION);
    filter.addAction(UpdateIntent.PLT_MEASUREMENT_ACTION);

    broadcastReceiver = new BroadcastReceiver() {

        @Override/*  www  . j  av  a2  s  .  c  om*/
        public void onReceive(Context context, Intent intent) {
            Logger.d(intent.getAction() + " RECEIVED");
            if (intent.getAction().equals(UpdateIntent.MEASUREMENT_ACTION)) {
                handleMeasurement();

            } else if (intent.getAction().equals(UpdateIntent.GCM_MEASUREMENT_ACTION)) {
                try {
                    JSONObject json = new JSONObject(
                            intent.getExtras().getString(UpdateIntent.MEASUREMENT_TASK_PAYLOAD));
                    Logger.d("MeasurementScheduler -> GCMManager: json task Value is " + json);
                    if (json != null && MeasurementTask.getMeasurementTypes().contains(json.get("type"))) {

                        try {
                            MeasurementTask task = MeasurementJsonConvertor.makeMeasurementTaskFromJson(json);
                            task.getDescription().priority = MeasurementTask.GCM_PRIORITY;
                            task.getDescription().startTime = new Date(System.currentTimeMillis() - 1000);
                            task.getDescription().endTime = new Date(System.currentTimeMillis() + (600 * 1000));
                            task.generateTaskID();
                            task.getDescription().key = Config.SERVER_TASK_CLIENT_KEY;
                            submitTask(task);
                        } catch (IllegalArgumentException e) {
                            Logger.w("MeasurementScheduler -> GCM : Could not create task from JSON: " + e);
                        }
                    }

                } catch (JSONException e) {
                    Logger.e(
                            "MeasurementSchedule -> GCMManager : Got exception during converting GCM json to MeasurementTask",
                            e);
                }

            } else if (intent.getAction().equals(UpdateIntent.MEASUREMENT_PROGRESS_UPDATE_ACTION)) {
                String taskid = intent.getStringExtra(UpdateIntent.TASKID_PAYLOAD);
                String taskKey = intent.getStringExtra(UpdateIntent.CLIENTKEY_PAYLOAD);
                int priority = intent.getIntExtra(UpdateIntent.TASK_PRIORITY_PAYLOAD,
                        MeasurementTask.INVALID_PRIORITY);

                Logger.e(
                        intent.getStringExtra(UpdateIntent.TASK_STATUS_PAYLOAD) + " " + taskid + " " + taskKey);
                if (intent.getStringExtra(UpdateIntent.TASK_STATUS_PAYLOAD).equals(Config.TASK_FINISHED)) {
                    tasksStatus.put(taskid, TaskStatus.FINISHED);
                    Parcelable[] results = intent.getParcelableArrayExtra(UpdateIntent.RESULT_PAYLOAD);
                    if (results != null) {
                        sendResultToClient(results, priority, taskKey, taskid);

                        for (Object obj : results) {
                            try {
                                MeasurementResult result = (MeasurementResult) obj;
                                /**
                                 * Nullify the additional parameters in MeasurmentDesc, or the results won't be
                                 * accepted by GAE server
                                 */
                                result.getMeasurementDesc().parameters = null;
                                String jsonResult = MeasurementJsonConvertor.encodeToJson(result).toString();
                                saveResultToFile(jsonResult);
                            } catch (JSONException e) {
                                Logger.e("Error converting results to json format", e);
                            }
                        }
                    }
                    handleMeasurement();
                } else if (intent.getStringExtra(UpdateIntent.TASK_STATUS_PAYLOAD).equals(Config.TASK_PAUSED)) {
                    tasksStatus.put(taskid, TaskStatus.PAUSED);
                } else if (intent.getStringExtra(UpdateIntent.TASK_STATUS_PAYLOAD)
                        .equals(Config.TASK_STOPPED)) {
                    tasksStatus.put(taskid, TaskStatus.SCHEDULED);
                } else if (intent.getStringExtra(UpdateIntent.TASK_STATUS_PAYLOAD)
                        .equals(Config.TASK_CANCELED)) {
                    tasksStatus.put(taskid, TaskStatus.CANCELLED);
                    Parcelable[] results = intent.getParcelableArrayExtra(UpdateIntent.RESULT_PAYLOAD);
                    if (results != null) {
                        sendResultToClient(results, priority, taskKey, taskid);
                    }
                } else if (intent.getStringExtra(UpdateIntent.TASK_STATUS_PAYLOAD)
                        .equals(Config.TASK_STARTED)) {
                    tasksStatus.put(taskid, TaskStatus.RUNNING);
                } else if (intent.getStringExtra(UpdateIntent.TASK_STATUS_PAYLOAD)
                        .equals(Config.TASK_RESUMED)) {
                    tasksStatus.put(taskid, TaskStatus.RUNNING);
                }
            } else if (intent.getAction().equals(UpdateIntent.CHECKIN_ACTION)
                    || intent.getAction().equals(UpdateIntent.CHECKIN_RETRY_ACTION)) {
                Logger.d("Checkin intent received");
                handleCheckin();
            }
        }
    };
    this.registerReceiver(broadcastReceiver, filter);
}

From source file:com.codefollower.lealone.omid.tso.TSOTestBase.java

@Before
public void setupTSO() throws Exception {
    if (!LocalBookKeeper.waitForServerUp("localhost:2181", 10000)) {
        throw new Exception("Error starting zookeeper/bookkeeper");
    }//w  ww.j  a  v a  2s . c om

    /*
     * TODO: Fix LocalBookKeeper to wait until the bookies are up
     * instead of waiting only until the zookeeper server is up.
     */
    Thread.sleep(500);

    LOG.info("Starting TSO");
    tso = new TSOServer(TSOServerConfig.parseConfig(new String[] { "-zk", "127.0.0.1:2181", "-port", "1234",
            "-ha", recoveryEnabled() + "", "-ensemble", "4", "-quorum", "2", "-batch", "0" }));
    tsoExecutor = Executors.newSingleThreadExecutor();
    tsoExecutor.execute(tso);
    TestUtils.waitForSocketListening("localhost", 1234, 100);
    LOG.info("Finished loading TSO");

    state = tso.getState();

    Thread.currentThread().setName("JUnit Thread");

    setupClient();
}

From source file:com.meltmedia.cadmium.core.worker.ConfigCoordinatedWorkerImpl.java

@Override
public void killUpdate() {
    IOUtils.closeQuietly(this);
    pool = Executors.newSingleThreadExecutor();
}

From source file:com.sixt.service.framework.kafka.messaging.KafkaIntegrationTest.java

@Ignore("long running test")
@Test/*  w ww  . j a va 2s. c om*/
public void partitionAssignmentChange() throws InterruptedException {
    ServiceProperties serviceProperties = new ServiceProperties();
    serviceProperties.initialize(new String[] {}); // Reads environment variables set by DockerComposeHelper

    // Topics are created with 3 partitions - see docker-compose-integrationtest.yml
    Topic ping = new Topic("ping");
    Topic pong = new Topic("pong");

    Producer producer = new ProducerFactory(serviceProperties).createProducer();

    final AtomicBoolean produceMessages = new AtomicBoolean(true);
    final AtomicInteger sentMessages = new AtomicInteger(0);

    final AtomicInteger receivedMessagesConsumer1 = new AtomicInteger(0);
    final CountDownLatch firstMessageProcessedConsumer1 = new CountDownLatch(1);

    final AtomicInteger receivedMessagesConsumer2 = new AtomicInteger(0);
    final CountDownLatch firstMessageProcessedConsumer2 = new CountDownLatch(1);

    final AtomicInteger receivedMessagesConsumer3 = new AtomicInteger(0);
    final CountDownLatch firstMessageProcessedConsumer3 = new CountDownLatch(1);

    // Produce messages until test tells producer to stop.
    ExecutorService producerExecutor = Executors.newSingleThreadExecutor();
    producerExecutor.submit(new Runnable() {
        @Override
        public void run() {
            OrangeContext context = new OrangeContext();
            Sleeper sleeper = new Sleeper();

            try {
                while (produceMessages.get()) {
                    String key = RandomStringUtils.randomAscii(5);
                    SayHelloToCmd payload = SayHelloToCmd.newBuilder().setName(key).build();

                    Message request = Messages.requestFor(ping, pong, key, payload, context);

                    producer.send(request);
                    sentMessages.incrementAndGet();

                    sleeper.sleepNoException(250);
                }
            } catch (Throwable t) {
                logger.error("Exception in producer loop", t);
            }
        }
    });

    // Start first producer. It should get all 3 partitions assigned.
    Consumer consumer1 = consumerFactoryWithHandler(serviceProperties, SayHelloToCmd.class,
            new MessageHandler<SayHelloToCmd>() {
                @Override
                public void onMessage(Message<SayHelloToCmd> message, OrangeContext context) {
                    receivedMessagesConsumer1.incrementAndGet();
                    firstMessageProcessedConsumer1.countDown();
                }
            }).consumerForTopic(ping, new DiscardFailedMessages());

    // wait until consumer 1 is up.
    firstMessageProcessedConsumer1.await();
    Thread.sleep(5000); // consume some messages

    // Now, start second processor. It should get at least one partition assigned.
    Consumer consumer2 = consumerFactoryWithHandler(serviceProperties, SayHelloToCmd.class,
            new MessageHandler<SayHelloToCmd>() {
                @Override
                public void onMessage(Message<SayHelloToCmd> message, OrangeContext context) {
                    receivedMessagesConsumer2.incrementAndGet();
                    firstMessageProcessedConsumer2.countDown();
                }
            }).consumerForTopic(ping, new DiscardFailedMessages());

    // wait until the second consumer is up.
    firstMessageProcessedConsumer2.await();
    Thread.sleep(5000); // let both consumers run a bit

    brutallyKillConsumer("pool-14-thread-1"); // consumer2 thread, HACKY: if this is too brittle, change the test to shutdown()

    //Need to wait a bit longer while Kafka "restabilizes the group" after consumer 2 was killed.
    // -> Consumer 1 should now get all three partitions back again.
    Thread.sleep(30000); // must be > than max.poll.interval.ms

    // Now, start third processor. It should get at least one partition assigned.
    Consumer consumer3 = consumerFactoryWithHandler(serviceProperties, SayHelloToCmd.class,
            new MessageHandler<SayHelloToCmd>() {
                @Override
                public void onMessage(Message<SayHelloToCmd> message, OrangeContext context) {
                    receivedMessagesConsumer3.incrementAndGet();
                    firstMessageProcessedConsumer3.countDown();
                }
            }).consumerForTopic(ping, new DiscardFailedMessages());
    firstMessageProcessedConsumer3.await();
    Thread.sleep(5000);

    // Now shut down the first consumer.
    consumer1.shutdown();
    Thread.sleep(10000);

    // Stop the producer.
    produceMessages.set(false);
    producer.shutdown();
    producerExecutor.shutdown();

    Thread.sleep(3000); // give the remaining consumer the chance to consume all messages
    consumer3.shutdown(); // no assignment any longer

    // Finally, the assertions:
    int receivedMessagesTotal = receivedMessagesConsumer1.get() + receivedMessagesConsumer2.get()
            + receivedMessagesConsumer3.get();
    assertEquals(sentMessages.get(), receivedMessagesTotal);

    assertTrue(receivedMessagesConsumer1.get() > 0);
    assertTrue(receivedMessagesConsumer2.get() > 0);
    assertTrue(receivedMessagesConsumer3.get() > 0);
}

From source file:org.apache.streams.components.http.provider.SimpleHttpProvider.java

@Override
public void prepare(Object configurationObject) {

    mapper = StreamsJacksonMapper.getInstance();

    uriBuilder = new URIBuilder().setScheme(this.configuration.getProtocol())
            .setHost(this.configuration.getHostname()).setPort(this.configuration.getPort().intValue())
            .setPath(this.configuration.getResourcePath());

    SSLContextBuilder builder = new SSLContextBuilder();
    SSLConnectionSocketFactory sslsf = null;
    try {//  ww  w . ja v a  2 s . com
        builder.loadTrustMaterial(null, new TrustSelfSignedStrategy());
        sslsf = new SSLConnectionSocketFactory(builder.build(),
                SSLConnectionSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
    } catch (NoSuchAlgorithmException e) {
        LOGGER.warn(e.getMessage());
    } catch (KeyManagementException e) {
        LOGGER.warn(e.getMessage());
    } catch (KeyStoreException e) {
        LOGGER.warn(e.getMessage());
    }

    httpclient = HttpClients.custom().setSSLSocketFactory(sslsf).build();

    executor = Executors.newSingleThreadExecutor();

}

From source file:io.fabric8.tooling.archetype.commands.ArchetypeCreateAction.java

/**
 * Fetches archetype from the configured repositories
 * TODO: make this code available to hawt.io/JMX too
 *
 * @param archetype/*  www  . j a v  a2 s  .  co  m*/
 * @return
 */
private InputStream fetchArchetype(Archetype archetype) throws IOException {
    MavenConfigurationImpl config = new MavenConfigurationImpl(
            new PropertiesPropertyResolver(System.getProperties()), "org.ops4j.pax.url.mvn");
    config.setSettings(new MavenSettingsImpl(config.getSettingsFileUrl(), config.useFallbackRepositories()));
    DownloadManager dm = new DownloadManager(config, Executors.newSingleThreadExecutor());

    final CountDownLatch latch = new CountDownLatch(1);
    DownloadFuture df = dm.download(
            String.format("mvn:%s/%s/%s", archetype.groupId, archetype.artifactId, archetype.version));
    df.addListener(new FutureListener<DownloadFuture>() {
        @Override
        public void operationComplete(DownloadFuture future) {
            latch.countDown();
        }
    });

    try {
        latch.await(30, TimeUnit.SECONDS);
    } catch (InterruptedException e) {
        System.err.println("Failed to download " + archetype);
        throw new IOException(e.getMessage(), e);
    }
    System.out.println("Downloaded archetype (" + df.getFile() + ")");

    return new FileInputStream(df.getFile());
}

From source file:li.barter.chat.ChatService.java

@Override
public void onCreate() {
    super.onCreate();
    SharedPreferenceHelper.registerSharedPreferencesChangedListener(
            ChatNotificationHelper.getInstance(this).getOnSharedPreferenceChangeListener());
    mChatDateFormatter = new DateFormatter(AppConstants.TIMESTAMP_FORMAT, AppConstants.CHAT_TIME_FORMAT);
    mMessageDateFormatter = new DateFormatter(AppConstants.TIMESTAMP_FORMAT, AppConstants.MESSAGE_TIME_FORMAT);
    mRequestQueue = ((IVolleyHelper) getApplication()).getRequestQueue();
    mVolleyCallbacks = new VolleyCallbacks(mRequestQueue, this);
    mCurrentConnectMultiplier = 0;/*from   w ww.ja  va  2 s .com*/
    mHandler = new Handler();
    mChatProcessor = Executors.newSingleThreadExecutor();
    mChatProcessTaskBuilder = new Builder(this);
}

From source file:com.amazon.janusgraph.example.MarvelGraphFactory.java

public static void load(final JanusGraph graph, final int rowsToLoad, final boolean report) throws Exception {

    JanusGraphManagement mgmt = graph.openManagement();
    if (mgmt.getGraphIndex(CHARACTER) == null) {
        final PropertyKey characterKey = mgmt.makePropertyKey(CHARACTER).dataType(String.class).make();
        mgmt.buildIndex(CHARACTER, Vertex.class).addKey(characterKey).unique().buildCompositeIndex();
    }//from  w  w  w . jav a 2 s .  co  m
    if (mgmt.getGraphIndex(COMIC_BOOK) == null) {
        final PropertyKey comicBookKey = mgmt.makePropertyKey(COMIC_BOOK).dataType(String.class).make();
        mgmt.buildIndex(COMIC_BOOK, Vertex.class).addKey(comicBookKey).unique().buildCompositeIndex();
        mgmt.makePropertyKey(WEAPON).dataType(String.class).make();
        mgmt.makeEdgeLabel(APPEARED).multiplicity(Multiplicity.MULTI).make();
    }
    mgmt.commit();

    ClassLoader classLoader = MarvelGraphFactory.class.getClassLoader();
    URL resource = classLoader.getResource("META-INF/marvel.csv");
    int line = 0;
    Map<String, Set<String>> comicToCharacter = new HashMap<>();
    Map<String, Set<String>> characterToComic = new HashMap<>();
    Set<String> characters = new HashSet<>();
    BlockingQueue<Runnable> creationQueue = new LinkedBlockingQueue<>();
    try (CSVReader reader = new CSVReader(new InputStreamReader(resource.openStream()))) {
        String[] nextLine;
        while ((nextLine = reader.readNext()) != null && line < rowsToLoad) {
            line++;
            String comicBook = nextLine[1];
            String[] characterNames = nextLine[0].split("/");
            if (!comicToCharacter.containsKey(comicBook)) {
                comicToCharacter.put(comicBook, new HashSet<String>());
            }
            List<String> comicCharacters = Arrays.asList(characterNames);
            comicToCharacter.get(comicBook).addAll(comicCharacters);
            characters.addAll(comicCharacters);

        }
    }

    for (String character : characters) {
        creationQueue.add(new CharacterCreationCommand(character, graph));
    }

    BlockingQueue<Runnable> appearedQueue = new LinkedBlockingQueue<>();
    for (String comicBook : comicToCharacter.keySet()) {
        creationQueue.add(new ComicBookCreationCommand(comicBook, graph));
        Set<String> comicCharacters = comicToCharacter.get(comicBook);
        for (String character : comicCharacters) {
            AppearedCommand lineCommand = new AppearedCommand(graph, new Appeared(character, comicBook));
            appearedQueue.add(lineCommand);
            if (!characterToComic.containsKey(character)) {
                characterToComic.put(character, new HashSet<String>());
            }
            characterToComic.get(character).add(comicBook);
        }
        REGISTRY.histogram("histogram.comic-to-character").update(comicCharacters.size());
    }

    int maxAppearances = 0;
    String maxCharacter = "";
    for (String character : characterToComic.keySet()) {
        Set<String> comicBookSet = characterToComic.get(character);
        int numberOfAppearances = comicBookSet.size();
        REGISTRY.histogram("histogram.character-to-comic").update(numberOfAppearances);
        if (numberOfAppearances > maxAppearances) {
            maxCharacter = character;
            maxAppearances = numberOfAppearances;
        }
    }
    LOG.info("Character {} has most appearances at {}", maxCharacter, maxAppearances);

    ExecutorService executor = Executors.newFixedThreadPool(POOL_SIZE);
    for (int i = 0; i < POOL_SIZE; i++) {
        executor.execute(new BatchCommand(graph, creationQueue));
    }
    executor.shutdown();
    while (!executor.awaitTermination(60, TimeUnit.SECONDS)) {
        LOG.info("Awaiting:" + creationQueue.size());
        if (report) {
            REPORTER.report();
        }
    }

    executor = Executors.newSingleThreadExecutor();
    executor.execute(new BatchCommand(graph, appearedQueue));

    executor.shutdown();
    while (!executor.awaitTermination(60, TimeUnit.SECONDS)) {
        LOG.info("Awaiting:" + appearedQueue.size());
        if (report) {
            REPORTER.report();
        }
    }
    LOG.info("MarvelGraphFactory.load complete");
}

From source file:com.uwsoft.editor.proxy.ResolutionManager.java

public void createNewResolution(ResolutionEntryVO resolutionEntryVO) {
    ProjectManager projectManager = facade.retrieveProxy(ProjectManager.NAME);
    projectManager.getCurrentProjectInfoVO().resolutions.add(resolutionEntryVO);
    ExecutorService executor = Executors.newSingleThreadExecutor();
    executor.execute(() -> {// w  ww .  java 2s.c o  m
        // create new folder structure
        String projPath = projectManager.getCurrentProjectPath();
        String sourcePath = projPath + "/" + "assets/orig/images";
        String targetPath = projPath + "/" + "assets/" + resolutionEntryVO.name + "/images";
        createIfNotExist(sourcePath);
        createIfNotExist(projPath + "/" + "assets/" + resolutionEntryVO.name + "/pack");
        copyTexturesFromTo(sourcePath, targetPath);
        int resizeWarnings = resizeTextures(targetPath, resolutionEntryVO);
        rePackProjectImages(resolutionEntryVO);
        createResizedAnimations(resolutionEntryVO);
        changePercentBy(5);
        if (resizeWarnings > 0) {
            DialogUtils.showOKDialog(Sandbox.getInstance().getUIStage(), "Warning", resizeWarnings
                    + " images were not resized for smaller resolutions due to already small size ( < 3px )");
        }
        Overlap2DFacade.getInstance().sendNotification(RESOLUTION_LIST_CHANGED);
    });
    executor.execute(() -> {
        try {
            Thread.sleep(500);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        projectManager.saveCurrentProject();
        //            handler.progressComplete();
    });
    executor.shutdown();
}

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

@Before
public void setup() {
    resourceCache = mock(ResourceCache.class);
    when(resourceCache.getProductCacheDirectory()).thenReturn(productCacheDirectory);
    eventPublisher = mock(DownloadsStatusEventPublisher.class);
    eventListener = mock(DownloadsStatusEventListener.class);
    downloadStatusInfo = new DownloadStatusInfoImpl();

    downloadMgr = new ReliableResourceDownloadManager(resourceCache, eventPublisher, eventListener,
            downloadStatusInfo, Executors.newSingleThreadExecutor());

}