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.metamx.druid.indexing.coordinator.TaskLifecycleTest.java

@Before
public void setUp() {
    EmittingLogger.registerEmitter(EasyMock.createMock(ServiceEmitter.class));

    tmp = Files.createTempDir();//from  w  w w.  j  a v a  2 s .c  o m

    ts = new HeapMemoryTaskStorage();
    tl = new TaskLockbox(ts);
    tq = new TaskQueue(ts, tl);
    mdc = newMockMDC();
    tac = new LocalTaskActionClientFactory(ts, new TaskActionToolbox(tq, tl, mdc, newMockEmitter()));

    tb = new TaskToolboxFactory(new TaskConfig() {
        @Override
        public String getBaseDir() {
            return tmp.toString();
        }

        @Override
        public int getDefaultRowFlushBoundary() {
            return 50000;
        }

        @Override
        public String getHadoopWorkingPath() {
            return null;
        }
    }, tac, newMockEmitter(), null, // s3 client
            new DataSegmentPusher() {
                @Override
                public DataSegment push(File file, DataSegment segment) throws IOException {
                    return segment;
                }
            }, new DataSegmentKiller() {
                @Override
                public void kill(DataSegment segments) throws SegmentLoadingException {

                }
            }, null, // segment announcer
            null, // new segment server view
            null, // query runner factory conglomerate corporation unionized collective
            null, // monitor scheduler
            new DefaultObjectMapper());

    tr = new ThreadPoolTaskRunner(tb, Executors.newSingleThreadExecutor());

    tc = new TaskConsumer(tq, tr, tac, newMockEmitter());
    tsqa = new TaskStorageQueryAdapter(ts);

    tq.start();
    tc.start();
}

From source file:net.jotel.ws.client.WebSocketClientTest.java

@Test
public void reconnect() throws Exception {

    final List<Exception> exceptions = new ArrayList<Exception>();

    URI uri = new URI("ws://not-existing-domain-name:8080/websocket/ws/subscribe");
    final WebSocketClient c = new WebSocketClient();
    c.setWebSocketUri(uri);/* w  w  w .j ava 2 s. c om*/
    c.setReconnectEnabled(true);
    c.setReconnectInterval(100L);
    c.setReconnectAttempts(2);
    c.addListener(new WebSocketListener() {
        @Override
        public void onMessage(String message) {
        }

        @Override
        public void onMessage(byte[] message) {
        }

        @Override
        public void onError(Exception ex) {
            exceptions.add(ex);
        }

        @Override
        public void onClose(Integer statusCode, String message) {
            // TODO Auto-generated method stub

        }

        @Override
        public void onConnect() {
            // TODO Auto-generated method stub

        }
    });

    try {
        c.connect();
        fail("Expected WebSocketException");
    } catch (WebSocketException ex) {
        // expected
        assertEquals(3, exceptions.size());

        for (Exception e : exceptions) {
            Throwable rootCause = ExceptionUtils.getRootCause(e);
            if (rootCause == null) {
                rootCause = e;
            }

            assertTrue(rootCause instanceof UnknownHostException);
        }
    }

    exceptions.clear();
    c.setReconnectAttempts(0);

    try {
        c.connect();
        fail("Expected WebSocketException");
    } catch (WebSocketException ex) {
        // expected
        assertEquals(1, exceptions.size());

        for (Exception e : exceptions) {
            Throwable rootCause = ExceptionUtils.getRootCause(e);
            if (rootCause == null) {
                rootCause = e;
            }

            assertTrue(rootCause instanceof UnknownHostException);
        }
    }

    exceptions.clear();
    c.setReconnectAttempts(-1);

    ExecutorService executor = Executors.newSingleThreadExecutor();

    Future<?> future = executor.submit(new Runnable() {
        @Override
        public void run() {
            try {
                c.connect();
                fail("Expected WebSocketException");
            } catch (WebSocketException ex) {
                throw new UnhandledException(ex);
            }
        }
    });

    Thread.sleep(2000L);

    c.setReconnectEnabled(false);

    Thread.sleep(2000L);

    executor.shutdown();
    assertTrue(executor.awaitTermination(1, TimeUnit.SECONDS));

    try {
        future.get();
        fail("Expected WebSocketException");
    } catch (Exception ex) {
        // expected
        assertTrue(exceptions.size() > 1);

        for (Exception e : exceptions) {
            Throwable rootCause = ExceptionUtils.getRootCause(e);
            if (rootCause == null) {
                rootCause = e;
            }

            assertTrue(rootCause instanceof UnknownHostException);
        }
    }
}

From source file:com.sonymobile.jenkins.plugins.lenientshutdown.ShutdownManageLink.java

/**
 * Toggles the flag and prepares for lenient shutdown if needed.
 *
 *//*ww w .j ava  2 s .c  o m*/
public void performToggleGoingToShutdown() {
    toggleGoingToShutdown();
    if (isGoingToShutdown()) {
        ExecutorService service = new SecurityContextExecutorService(Executors.newSingleThreadExecutor());
        service.submit(new Runnable() {
            @Override
            public void run() {
                permittedQueueIds.clear();
                activeQueueIds.clear();
                whiteListedQueueIds.clear();
                permittedQueueIds.addAll(QueueUtils.getPermittedQueueItemIds());
                permittedQueueIds.addAll(QueueUtils.getRunningProjectQueueIds());
                activeQueueIds.addAll(permittedQueueIds);
                analyzing = false;
            }
        });
    }
}

From source file:at.ac.tuwien.detlef.activities.MainActivity.java

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    startSettingsActivityIfNoDeviceIdSet();

    setContentView(R.layout.main_activity_layout);

    boolean showProgressDialog = false;

    /*/*from   w  w  w  . j  a va2  s .  c  o  m*/
     * Old Activity is recreated and the Activity has not been removed from
     * memory. The latter part is important because if it was, we have to
     * abort any ongoing refresh.
     */
    if ((savedInstanceState != null) && (refreshBg != null)) {
        curPodSync = new AtomicInteger(savedInstanceState.getInt(KEY_CUR_POD_SYNC, 0));
        numPodSync = new AtomicInteger(savedInstanceState.getInt(KEY_NUM_POD_SYNC, -1));
        showProgressDialog = savedInstanceState.getBoolean(KEY_SHOW_PROGRESS_DIALOG, false);
    } else {
        podcastHandler = new PodcastHandler();
        feedHandler = new FeedHandler();
        episodeActionHandler = new EpisodeActionHandler();
    }

    if (refreshBg == null) {
        refreshBg = Executors.newSingleThreadExecutor();
    }

    MediaPlayerNotification.create(this, false, null);

    // Create the adapter that will return a fragment for each of the three
    // primary sections of the app.
    mSectionsPagerAdapter = new SectionsPagerAdapter(getSupportFragmentManager());

    // Set up the action bar.
    actionBar = getActionBar();
    actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);

    // Set up the ViewPager with the sections adapter.
    mViewPager = (ViewPager) findViewById(R.id.pager);
    mViewPager.setAdapter(mSectionsPagerAdapter);

    // When swiping between different sections, select the corresponding
    // tab.
    // We can also use ActionBar.Tab#select() to do this if we have a
    // reference to the Tab.
    mViewPager.setOnPageChangeListener(new ViewPager.SimpleOnPageChangeListener() {
        @Override
        public void onPageSelected(int position) {
            actionBar.setSelectedNavigationItem(position);
        }
    });

    // For each of the sections in the app, add a tab to the action bar.
    for (int i = 0; i < mSectionsPagerAdapter.getCount(); i++) {
        // Create a tab with text corresponding to the page title defined by
        // the adapter.
        // Also specify this Activity object, which implements the
        // TabListener interface, as the
        // listener for when this tab is selected.
        actionBar
                .addTab(actionBar.newTab().setText(mSectionsPagerAdapter.getPageTitle(i)).setTabListener(this));
    }

    /* Ready the progress dialog */
    progressDialog = new ProgressDialog(this);
    prepareProgressDialog();
    if ((numPodSync.get() != -1) && showProgressDialog) {
        progressDialog.show();
    }

    playlistDAO = Singletons.i().getPlaylistDAO();
}

From source file:com.o2d.pkayjava.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 w w  .j  ava 2  s. com
        // create new folder structure
        String projPath = projectManager.getCurrentWorkingPath() + "/"
                + projectManager.getCurrentProjectVO().projectName;
        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:de.dfki.iui.mmds.dialogue.SiamStateMachine.java

@Override
public boolean start() {
    isRunning = true;/*from w ww  .  jav  a  2  s .  c o  m*/
    ExecutorService executor = Executors.newSingleThreadExecutor();
    executor.execute(queueWorker);
    addListener(siamEvaluator);
    return super.start();
}

From source file:com.mirth.connect.connectors.ws.WebServiceConnectorService.java

private Future<WsdlInterface> importWsdlInterface(final WsdlProject wsdlProject, final URI newWsdlUrl,
        final WsdlLoader wsdlLoader) {
    ExecutorService executor = Executors.newSingleThreadExecutor();

    return executor.submit(new Callable<WsdlInterface>() {
        public WsdlInterface call() throws Exception {
            WsdlInterface[] wsdlInterfaces = WsdlInterfaceFactory.importWsdl(wsdlProject,
                    newWsdlUrl.toURL().toString(), false, wsdlLoader);
            return wsdlInterfaces[0];
        }/*from w w w  .ja  v  a2s .c o  m*/
    });
}

From source file:no.ntnu.idi.socialhitchhiking.map.GeoHelper.java

/**
 * Gets a {@link JSONArray} from the Google Maps API from a set of coordinates
 * @param lat//  w  w  w .j  ava2  s  .  co  m
 * @param lon
 * @param maxResults
 * @return JSONArray of locations
 */
private static JSONArray getJSONArrayFromLocation(final double lat, final double lon, int maxResults) {
    ExecutorService executor = Executors.newSingleThreadExecutor();

    Callable<JSONArray> callable = new Callable<JSONArray>() {
        @Override
        public JSONArray call() throws IOException {
            String urlStr = "http://maps.googleapis.com/maps/api/geocode/json?latlng=" + lat + "," + lon
                    + "&sensor=false";
            String response = "";
            HttpClient client = new DefaultHttpClient();
            HttpResponse hr = client.execute(new HttpGet(urlStr));
            HttpEntity entity = hr.getEntity();
            BufferedReader br = new BufferedReader(new InputStreamReader(entity.getContent()));
            String buff = null;
            while ((buff = br.readLine()) != null)
                response += buff;

            br.close();
            JSONArray responseArray = null;
            try {
                JSONObject jsonObject = new JSONObject(response);
                responseArray = jsonObject.getJSONArray("results");
            } catch (JSONException e) {
                return null;
            }
            return responseArray;
        }
    };
    Future<JSONArray> future = executor.submit(callable);
    JSONArray ret;
    try {
        ret = future.get();
    } catch (InterruptedException e) {
        // TODO Auto-generated catch block
        ret = null;
    } catch (ExecutionException e) {
        // TODO Auto-generated catch block
        ret = null;
    }

    return ret;
}