List of usage examples for java.util.concurrent Executor execute
void execute(Runnable command);
From source file:org.onosproject.store.cluster.messaging.impl.NettyMessagingManager.java
@Override public void registerHandler(String type, BiConsumer<Endpoint, byte[]> handler, Executor executor) { checkPermission(CLUSTER_WRITE);//from www .ja v a2s. co m handlers.put(type, message -> executor.execute(() -> handler.accept(message.sender(), message.payload()))); }
From source file:org.onosproject.store.cluster.messaging.impl.NettyMessagingManager.java
@Override public void registerHandler(String type, BiFunction<Endpoint, byte[], byte[]> handler, Executor executor) { checkPermission(CLUSTER_WRITE);/*from w ww .j a v a 2s .com*/ handlers.put(type, message -> executor.execute(() -> { byte[] responsePayload = null; Status status = Status.OK; try { responsePayload = handler.apply(message.sender(), message.payload()); } catch (Exception e) { status = Status.ERROR_HANDLER_EXCEPTION; } sendReply(message, status, Optional.ofNullable(responsePayload)); })); }
From source file:org.springframework.integration.jms.request_reply.RequestReplyScenariosWithTempReplyQueuesTests.java
@Test public void testConcurrently() throws Exception { ActiveMqTestUtils.prepare();/*ww w. j a v a 2s.c o m*/ ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext( "mult-producer-and-consumers-temp-reply.xml", this.getClass()); final RequestReplyExchanger gateway = context.getBean(RequestReplyExchanger.class); Executor executor = Executors.newFixedThreadPool(10); final int testNumbers = 100; final CountDownLatch latch = new CountDownLatch(testNumbers); final AtomicInteger failures = new AtomicInteger(); final AtomicInteger timeouts = new AtomicInteger(); final AtomicInteger missmatches = new AtomicInteger(); for (int i = 0; i < testNumbers; i++) { final int y = i; executor.execute(() -> { try { String reply = (String) gateway.exchange(new GenericMessage<String>(String.valueOf(y))) .getPayload(); if (!String.valueOf(y).equals(reply)) { missmatches.incrementAndGet(); } } catch (Exception e) { if (e instanceof MessageDeliveryException) { timeouts.incrementAndGet(); } else { failures.incrementAndGet(); } } // if (latch.getCount()%100 == 0){ // long count = testNumbers-latch.getCount(); // if (count > 0){ // print(failures, timeouts, missmatches, testNumbers-latch.getCount()); // } // } latch.countDown(); }); } latch.await(); print(failures, timeouts, missmatches, testNumbers); Thread.sleep(5000); assertEquals(0, missmatches.get()); assertEquals(0, failures.get()); assertEquals(0, timeouts.get()); context.close(); }
From source file:org.springframework.amqp.rabbit.listener.SimpleMessageListenerContainerTests.java
protected void setUpMockCancel(Channel channel, final List<Consumer> consumers) throws IOException { final Executor exec = Executors.newCachedThreadPool(); doAnswer(invocation -> {/*from w w w .j a va 2 s . co m*/ final String consTag = (String) invocation.getArguments()[0]; exec.execute(() -> consumers.get(Integer.parseInt(consTag)).handleCancelOk(consTag)); return null; }).when(channel).basicCancel(anyString()); }
From source file:com.google.android.apps.forscience.whistlepunk.DataControllerImpl.java
private <T> void background(Executor dataThread, final MaybeConsumer<T> onSuccess, final Callable<T> job) { dataThread.execute(new Runnable() { @Override/*from www . j a va 2 s . c om*/ public void run() { try { final T result = job.call(); mUiThread.execute(new Runnable() { @Override public void run() { onSuccess.success(result); } }); } catch (final Exception e) { mUiThread.execute(new Runnable() { @Override public void run() { onSuccess.fail(e); } }); } } }); }
From source file:org.nd4j.linalg.ops.OpExecutionerTests.java
@Test @Ignore/*from www .j a va 2 s .c o m*/ public void testDistance() throws Exception { INDArray matrix = Nd4j.rand(new int[] { 400, 10 }); INDArray rowVector = matrix.getRow(70); INDArray resultArr = Nd4j.zeros(400, 1); Executor executor = Executors.newSingleThreadExecutor(); executor.execute(new Runnable() { @Override public void run() { Nd4j.getExecutioner().exec(new EuclideanDistance(matrix, rowVector, resultArr, matrix.lengthLong()), -1); System.out.println("Ran!"); } }); Thread.sleep(600000); }
From source file:org.esigate.extension.parallelesi.IncludeElement.java
@Override public void onTagEnd(String tag, FutureParserContext ctx) throws IOException, HttpErrorPage { write = true;/*w w w . j a v a 2 s. c om*/ String src = includeTag.getAttribute("src"); String alt = includeTag.getAttribute("alt"); boolean ignoreError = "continue".equals(includeTag.getAttribute("onerror")); FutureElement current = ctx.getCurrent(); // write accumulated data into parent Executor executor = (Executor) ctx.getData(EsiRenderer.DATA_EXECUTOR); Future<CharSequence> result = null; IncludeTask task = new IncludeTask(includeTag, src, alt, ctx, current, ignoreError, fragmentReplacements, regexpReplacements, executor); if (executor == null) { // No threads. CharSequence content = task.call(); result = new CharSequenceFuture(content); } else { // Start processing in a new thread. RunnableFuture<CharSequence> r = new FutureTask<CharSequence>(task); executor.execute(r); result = r; } ctx.getCurrent().characters(result); }
From source file:me.calebjones.blogsite.network.PostDownloader.java
public void download(final List<String> postID) { final DatabaseManager databaseManager = new DatabaseManager(this); try {//from ww w.j a v a 2 s.co m final int num = postID.size() - 1; final CountDownLatch latch = new CountDownLatch(num); final Executor executor = Executors.newFixedThreadPool(15); for (int i = 1; i <= postID.size() - 1; i++) { final int count = i; final int index = Integer.parseInt(postID.get(i)); executor.execute(new Runnable() { @Override public void run() { try { if (index != 404) { String url = String.format(POST_URL, index); Request newReq = new Request.Builder().url(url).build(); Response newResp = BlogsiteApplication.getInstance().client.newCall(newReq) .execute(); if (!newResp.isSuccessful() && !(newResp.code() == 404) && !(newResp.code() == 403)) { Log.e("The Jones Theory", "Error: " + newResp.code() + "URL: " + url); LocalBroadcastManager.getInstance(PostDownloader.this) .sendBroadcast(new Intent(DOWNLOAD_FAIL)); throw new IOException(); } if (newResp.code() == 404) { return; } String resp = newResp.body().string(); JSONObject jObject = new JSONObject(resp); Posts item1 = new Posts(); //If the item is not a post break out of loop and ignore it if (!(jObject.optString("type").equals("post"))) { return; } item1.setTitle(jObject.optString("title")); item1.setContent(jObject.optString("content")); item1.setExcerpt(jObject.optString("excerpt")); item1.setPostID(jObject.optInt("ID")); item1.setURL(jObject.optString("URL")); //Parse the Date! String date = jObject.optString("date"); SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssZ"); Date newDate = format.parse(date); format = new SimpleDateFormat("yyyy-MM-dd"); date = format.format(newDate); item1.setDate(date); //Cuts out all the Child nodes and gets only the tags. JSONObject Tobj = new JSONObject(jObject.optString("tags")); JSONArray Tarray = Tobj.names(); String tagsList = null; if (Tarray != null && (Tarray.length() > 0)) { for (int c = 0; c < Tarray.length(); c++) { if (tagsList != null) { String thisTag = Tarray.getString(c); tagsList = tagsList + ", " + thisTag; } else { String thisTag = Tarray.getString(c); tagsList = thisTag; } } item1.setTags(tagsList); } else { item1.setTags(""); } JSONObject Cobj = new JSONObject(jObject.optString("categories")); JSONArray Carray = Cobj.names(); String catsList = null; if (Carray != null && (Carray.length() > 0)) { for (int c = 0; c < Carray.length(); c++) { if (catsList != null) { String thisCat = Carray.getString(c); catsList = catsList + ", " + thisCat; } else { String thisCat = Carray.getString(c); catsList = thisCat; } } item1.setCategories(catsList); } else { item1.setCategories(""); } Integer ImageLength = jObject.optString("featured_image").length(); if (ImageLength == 0) { item1.setFeaturedImage(null); } else { item1.setFeaturedImage(jObject.optString("featured_image")); } if (item1 != null) { databaseManager.addPost(item1); Log.d("PostDownloader", index + " database..."); double progress = ((double) count / num) * 100; setProgress((int) progress, item1.getTitle(), count); Intent intent = new Intent(DOWNLOAD_PROGRESS); intent.putExtra(PROGRESS, progress); intent.putExtra(NUMBER, num); intent.putExtra(TITLE, item1.getTitle()); LocalBroadcastManager.getInstance(PostDownloader.this).sendBroadcast(intent); } } } catch (IOException | JSONException | ParseException e) { if (SharedPrefs.getInstance().isFirstDownload()) { SharedPrefs.getInstance().setFirstDownload(false); } SharedPrefs.getInstance().setDownloading(false); e.printStackTrace(); } finally { latch.countDown(); } } }); } try { latch.await(); } catch (InterruptedException e) { if (SharedPrefs.getInstance().isFirstDownload()) { SharedPrefs.getInstance().setFirstDownload(false); } SharedPrefs.getInstance().setDownloading(false); LocalBroadcastManager.getInstance(this).sendBroadcast(new Intent(DOWNLOAD_FAIL)); mBuilder.setContentText("Download failed.").setSmallIcon(R.drawable.ic_action_file_download) .setAutoCancel(true).setProgress(0, 0, false).setOngoing(false); mNotifyManager.notify(NOTIF_ID, mBuilder.build()); throw new IOException(e); } if (SharedPrefs.getInstance().isFirstDownload()) { SharedPrefs.getInstance().setFirstDownload(false); } SharedPrefs.getInstance().setDownloading(false); Log.d("PostDownloader", "Broadcast Sent!"); Log.d("The Jones Theory", "download - Downloading = " + SharedPrefs.getInstance().isDownloading()); Intent mainActIntent = new Intent(this, MainActivity.class); PendingIntent clickIntent = PendingIntent.getActivity(this, 57836, mainActIntent, PendingIntent.FLAG_UPDATE_CURRENT); LocalBroadcastManager.getInstance(this).sendBroadcast(new Intent(DOWNLOAD_SUCCESS)); mBuilder.setContentText("Download complete").setSmallIcon(R.drawable.ic_action_done) .setProgress(0, 0, false).setContentIntent(clickIntent).setAutoCancel(true).setOngoing(false); mNotifyManager.notify(NOTIF_ID, mBuilder.build()); } catch (IOException e) { if (SharedPrefs.getInstance().isFirstDownload()) { SharedPrefs.getInstance().setFirstDownload(false); } SharedPrefs.getInstance().setLastRedownladTime(System.currentTimeMillis()); SharedPrefs.getInstance().setDownloading(false); e.printStackTrace(); LocalBroadcastManager.getInstance(this).sendBroadcast(new Intent(DOWNLOAD_FAIL)); mBuilder.setContentText("Download failed.").setProgress(0, 0, false).setAutoCancel(true) .setOngoing(false); mNotifyManager.notify(NOTIF_ID, mBuilder.build()); } }
From source file:me.code4fun.roboq.Request.java
public void execute(Executor executor, final Callback cb) { Executor executor1 = selectValue(executor, prepared != null ? prepared.executor : null, null); if (executor1 == null) throw new NullPointerException("The executor is null"); executor1.execute(new Runnable() { @Override/*from www . ja v a 2s. c o m*/ public void run() { Response resp; Exception error; try { resp = execute(); error = null; } catch (Exception e) { resp = null; error = e; } if (cb != null) cb.onResponse(Request.this, resp, error); } }); }
From source file:de.taimos.httputils.HTTPRequest.java
private void executeAsync(final Executor executor, final HttpUriRequest req, final HTTPResponseCallback cb) { final Runnable execute = new Runnable() { @Override//from w ww. j ava 2 s .c o m public void run() { final HttpResponse res; try { res = HTTPRequest.this.execute(req); } catch (final Exception e) { cb.fail(e); return; } cb.response(res); } }; executor.execute(execute); }