@Override public void run() { assertSame(this, Thread.currentThread()); try { while (true) { Request request = requestQueue.take(); Object result; try { result = invokeMethod(request.methodName, request.arguments); } catch (ThreadDeath death) { return; } catch (InvocationTargetException exception) { responseQueue.put(new Response(request.methodName, null, exception.getTargetException())); continue; } catch (Throwable throwable) { responseQueue.put(new Response(request.methodName, null, throwable)); continue; } responseQueue.put(new Response(request.methodName, result, null)); } } catch (ThreadDeath death) { return; } catch (InterruptedException ignored) { // SynchronousQueue sometimes throws InterruptedException while the threads are stopping. } catch (Throwable uncaught) { this.uncaughtThrowable = uncaught; } }
@Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { SynchronousQueue<Boolean> queue = new SynchronousQueue<Boolean>(); timeoutService.start(queue); Boolean initializedResult; try { initializedResult = queue.poll(5, TimeUnit.SECONDS); } catch (InterruptedException e) { throw new ServletException(e); } resp.getWriter().append("Initialized:" + initializedResult); resp.getWriter().append("\n"); // wait for the request scope created for the async method invocation to be destroyed try { new Timer() .setDelay(2000l) .addStopCondition( new StopCondition() { public boolean isSatisfied() { return observingBean.isDestroyedCalled(); } }) .start(); } catch (InterruptedException e) { throw new ServletException(e); } resp.getWriter().append("Destroyed:" + observingBean.isDestroyedCalled()); resp.setContentType("text/plain"); }
/** * Offer a message that may have a synchronous consumer waiting. * * @param destination Queue name * @param message Received message. Can be NetFault or NetNotification */ protected boolean offerPollResponse(String destination, NetMessage message) { synchronized (_syncSubscriptions) { SynchronousQueue<NetMessage> synchronousQueue = pendingPolls.get(destination); if (synchronousQueue != null) { return synchronousQueue.offer(message); } return false; } }
public void concreteWriteReadTest() { String tainted = TelephonyManager.getDeviceId(); SynchronousQueue<String> q = new SynchronousQueue<String>(); q.add(tainted); // not implemented for SynchronousQueue: q.element(); String taintedElement3 = q.poll(); ConnectionManager cm = new ConnectionManager(); cm.publish(taintedElement3); }
/** * Obtain a queue message synchronously. * * @param queueName Name of the queue from where to retrieve a message * @param timeout Timeout, in milliseconds. When timeout is reached a TimeoutException is thrown. * Zero means that the client wants to wait forever. A negative value means that the client * doesn't want to wait if there are no messages is local agent's queue. * @param reserveTime Message reserve time, in milliseconds. Polled messages are reserved, by * default, for 15 minutes. If clients prefer a different reserve time , bigger or small, they * can specify it. * @param acceptRequest An AcceptRequest object used handling Accept messages. * @return A notification containing the queue message. Or null if timeout was a negative value * and there was no message in local agent's queue. */ public NetNotification poll( String queueName, long timeout, long reserveTime, AcceptRequest acceptRequest) throws Throwable { if (StringUtils.isBlank(queueName)) throw new IllegalArgumentException("Mal-formed Poll request. queueName is blank."); NetPoll poll = new NetPoll(queueName, timeout); NetAction action = new NetAction(ActionType.POLL); action.setPollMessage(poll); NetMessage message = buildMessage(action); SynchronousQueue<NetMessage> synQueue = new SynchronousQueue<NetMessage>(); synchronized (_syncSubscriptions) { if (_syncSubscriptions.containsKey(queueName)) throw new IllegalArgumentException("Queue " + queueName + " has already a poll runnig."); _syncSubscriptions.put(queueName, message); pendingPolls.put(queueName, synQueue); } if (reserveTime > 0) { message.getHeaders().put(Headers.RESERVE_TIME, reserveTime + ""); } if (acceptRequest != null) { poll.setActionId(acceptRequest.getActionId()); PendingAcceptRequestsManager.addAcceptRequest(acceptRequest); } getNetHandler().sendMessage(message); NetMessage receivedMsg = synQueue.take(); synchronized (_syncSubscriptions) { _syncSubscriptions.remove(queueName); pendingPolls.remove(queueName); } if (receivedMsg == BrokerProtocolHandler.TimeoutUnblockNotification) throw new TimeoutException(); if (receivedMsg == BrokerProtocolHandler.NoMessageUnblockNotification) return null; NetNotification m = null; if (receivedMsg.getAction().getActionType().equals(ActionType.NOTIFICATION)) { m = receivedMsg.getAction().getNotificationMessage(); } else { log.error( "Poll unbloqued by a message that wasn't of any of the expeceted error nor a notification."); return null; } return m; }
public void onActivityResult(int resultCode, Intent data) { try { if (resultCode != Activity.RESULT_OK) { mFilePickerResult.put(""); return; } File file = new File(Environment.getExternalStorageDirectory(), sImageName); sImageName = ""; mFilePickerResult.put(file.getAbsolutePath()); } catch (InterruptedException e) { Log.i(LOGTAG, "error returning file picker result", e); } }
@Override public void messageArrived(String topic, MqttMessage message) throws Exception { final String METHOD = "messageArrived"; if (topic.equals(ServerTopic.RESPONSE.getName())) { LoggerUtility.log( Level.FINE, CLASS_NAME, METHOD, "Received response from IoT Foundation, topic (" + topic + ")"); String responsePayload = new String(message.getPayload(), "UTF-8"); JsonObject jsonResponse = new JsonParser().parse(responsePayload).getAsJsonObject(); try { String reqId = jsonResponse.get("reqId").getAsString(); LoggerUtility.fine(CLASS_NAME, METHOD, "reqId (" + reqId + "): " + jsonResponse.toString()); MqttMessage sentMsg = requests.remove(reqId); if (sentMsg != null) { queue.put(jsonResponse); } } catch (Exception e) { if (jsonResponse.get("reqId") == null) { LoggerUtility.warn( CLASS_NAME, METHOD, "The response " + "does not contain 'reqId' field (" + responsePayload + ")"); } else { LoggerUtility.log(Level.SEVERE, CLASS_NAME, METHOD, "Unexpected exception", e); } } } else { LoggerUtility.warn(CLASS_NAME, METHOD, "Unknown topic (" + topic + ")"); } }
private void runOnIcThread(Handler icHandler, final Runnable runnable) { if (DEBUG) { ThreadUtils.assertOnUiThread(); Log.d(LOGTAG, "runOnIcThread() on thread " + icHandler.getLooper().getThread().getName()); } Runnable runner = new Runnable() { @Override public void run() { try { Runnable queuedRunnable = mIcRunnableSync.take(); if (DEBUG && queuedRunnable != runnable) { throw new IllegalThreadStateException("sync error"); } queuedRunnable.run(); } catch (InterruptedException e) { } } }; try { // if we are not inside waitForUiThread(), runner will call the runnable icHandler.post(runner); // runnable will be called by either runner from above or waitForUiThread() mIcRunnableSync.put(runnable); } catch (InterruptedException e) { } finally { // if waitForUiThread() already called runnable, runner should not call it again icHandler.removeCallbacks(runner); } }
/** * After starting this class (start()), this method MAY be called to block the thread that created * the instance of this class. Otherwise, the thread will finish and the instance of this class * will be terminated. * * @throws InterruptedException unsuccessful join */ public void join() throws InterruptedException { // TODO: // initiate a graceful termination procedure (i.e., close()). log.info("joining"); @SuppressWarnings("unused") Object object = dispatcherJoin.take(); }
private void putNextValue(String value) { try { res.put(value); } catch (InterruptedException interEx) { Thread.currentThread().interrupt(); } }
private void readNextValue() { try { curValue = res.take(); } catch (InterruptedException interEx) { Thread.currentThread().interrupt(); } }
/** * Receives a response from this thread. * * @throws TimeoutException if this thread does not offer a response within a reasonable amount of * time * @throws AssertionFailedError if the given method name does not match the name of the method * this thread has called most recently */ private Response getResponse(String methodName) throws Exception { Response response = responseQueue.poll(TIMEOUT_MILLIS, TimeUnit.MILLISECONDS); if (response == null) { throw new TimeoutException(); } assertEquals(methodName, response.methodName); return response; }
/** * Causes this thread to call the named method, and asserts that this thread becomes blocked on * the lock-like object. The lock-like object must have a method equivalent to {@link * java.util.concurrent.locks.ReentrantLock#hasQueuedThread(Thread)}. */ public void callAndAssertBlocks(String methodName, Object... arguments) throws Exception { checkNotNull(methodName); checkNotNull(arguments); assertEquals(false, invokeMethod("hasQueuedThread", this)); sendRequest(methodName, arguments); Thread.sleep(DUE_DILIGENCE_MILLIS); assertEquals(true, invokeMethod("hasQueuedThread", this)); assertNull(responseQueue.poll()); }
public void finishDialog(String aReturn) { mInputs = null; mDialog = null; mSelected = null; try { mPromptQueue.put(aReturn); } catch (Exception ex) { } }
public static String waitForReturn() throws InterruptedException { String value; while (null == (value = mPromptQueue.poll(1, TimeUnit.MILLISECONDS))) { GeckoAppShell.processNextNativeEvent(); } return value; }
/** * Causes this thread to call the named method, and asserts that this thread thereby waits on the * given condition-like object. The lock-like object must have a method equivalent to {@link * java.util.concurrent.locks.ReentrantLock#hasWaiters(java.util.concurrent.locks.Condition)}, * except that the method parameter must accept whatever condition-like object is passed into this * method. */ public void callAndAssertWaits(String methodName, Object conditionLikeObject) throws Exception { checkNotNull(methodName); checkNotNull(conditionLikeObject); // TODO: Restore the following line when Monitor.hasWaiters() no longer acquires the lock. // assertEquals(false, invokeMethod("hasWaiters", conditionLikeObject)); sendRequest(methodName, conditionLikeObject); Thread.sleep(DUE_DILIGENCE_MILLIS); assertEquals(true, invokeMethod("hasWaiters", conditionLikeObject)); assertNull(responseQueue.poll()); }
public void endWaitForUiThread() { if (DEBUG) { ThreadUtils.assertOnUiThread(); Log.d(LOGTAG, "endWaitForUiThread()"); } try { mIcRunnableSync.put(mIcSignalRunnable); } catch (InterruptedException e) { } }
// Place an object in the sync queue, indicating that the calling thread is finished, // and any waiting thread may continue. Placing an Exception into the queue indicates // an error condition has occurred that should be handled by the waiting thread. private void finished(Object obj) { while (true) { try { queue.put(obj); break; } catch (InterruptedException e1) { // no-op } } }
@Test public void subscription() throws Exception { TestApplicationContext context = TestUtils.createTestApplicationContext(); SynchronousQueue<String> queue = new SynchronousQueue<String>(); TestBean testBean = new TestBean(queue); QueueChannel channel = new QueueChannel(); context.registerChannel("channel", channel); Message<String> message = new GenericMessage<String>("testing"); channel.send(message); assertNull(queue.poll()); MethodInvokingMessageHandler handler = new MethodInvokingMessageHandler(testBean, "foo"); PollingConsumer endpoint = new PollingConsumer(channel, handler); endpoint.setTrigger(new PeriodicTrigger(10)); context.registerEndpoint("testEndpoint", endpoint); context.refresh(); String result = queue.poll(2000, TimeUnit.MILLISECONDS); assertNotNull(result); assertEquals("testing", result); context.stop(); }
@Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { String filePickerResult = ""; if (data != null && resultCode == RESULT_OK) { try { ContentResolver cr = getContentResolver(); Uri uri = data.getData(); Cursor cursor = GeckoApp.mAppContext .getContentResolver() .query(uri, new String[] {OpenableColumns.DISPLAY_NAME}, null, null, null); String name = null; if (cursor != null) { try { if (cursor.moveToNext()) { name = cursor.getString(0); } } finally { cursor.close(); } } String fileName = "tmp_"; String fileExt = null; int period; if (name == null || (period = name.lastIndexOf('.')) == -1) { String mimeType = cr.getType(uri); fileExt = "." + GeckoAppShell.getExtensionFromMimeType(mimeType); } else { fileExt = name.substring(period); fileName = name.substring(0, period); } File file = File.createTempFile(fileName, fileExt, sGREDir); FileOutputStream fos = new FileOutputStream(file); InputStream is = cr.openInputStream(uri); byte[] buf = new byte[4096]; int len = is.read(buf); while (len != -1) { fos.write(buf, 0, len); len = is.read(buf); } fos.close(); filePickerResult = file.getAbsolutePath(); } catch (Exception e) { Log.e(LOG_FILE_NAME, "showing file picker", e); } } try { mFilePickerResult.put(filePickerResult); } catch (InterruptedException e) { Log.i(LOG_FILE_NAME, "error returning file picker result", e); } }
public void run() { for (Course course : Course.values()) { Food food = course.randomSelection(); try { waitPerson.placeOrder(this, food); // Blocks until course has been delivered: print(this + "eating " + placeSetting.take()); } catch (InterruptedException e) { print(this + "waiting for " + course + " interrupted"); break; } } print(this + "finished meal, leaving"); }
// Causes the caller thread to block until an object is placed in the sync queue/ // If an Exception is place in the queue, it this thrown by the calling thread. private void join() throws Exception { while (true) { Object result = null; try { result = queue.take(); if (result instanceof Exception) { throw (Exception) result; } break; } catch (InterruptedException e) { if (result != null) throw e; } } }
public Bitmap loadDrawable(final String imageUrl, final int page, final ImageCallback callback) { Bitmap bitmap = getBitmap(imageUrl); if (null != bitmap) { return bitmap; } try { taskQueue.put(new WorkItem(imageUrl, page, callback)); } catch (InterruptedException e) { e.printStackTrace(); } return null; }
public void waitForUiThread(Handler icHandler) { if (DEBUG) { ThreadUtils.assertOnThread(icHandler.getLooper().getThread(), AssertBehavior.THROW); Log.d( LOGTAG, "waitForUiThread() blocking on thread " + icHandler.getLooper().getThread().getName()); } try { Runnable runnable = null; do { runnable = mIcRunnableSync.take(); runnable.run(); } while (runnable != mIcSignalRunnable); } catch (InterruptedException e) { } }
@Test public void testGivenExecutorUsed() throws InterruptedException { // easily identifiable thread pool Executor executor = Executors.newSingleThreadExecutor( runnable -> { return new Thread(runnable, FireAsyncWithExecutorTest.class.getName()); }); request.fireAsync(new Request(), executor); final Response response = SYNCHRONIZER.poll(30, TimeUnit.SECONDS); assertTrue(REQUEST_RECEIVED.get()); assertNotNull(RESPONSE_RECEIVED.get()); assertEquals( FireAsyncWithExecutorTest.class.getName(), RESPONSE_RECEIVED.get().getThread().getName()); assertNotNull("Synchronization failed", response); assertEquals(FireAsyncWithExecutorTest.class.getName(), response.getThread().getName()); }
public void concreteWriteReadNegativeTest() { String tainted = TelephonyManager.getDeviceId(); String untainted = "Hello world!"; SynchronousQueue<String> q = new SynchronousQueue<String>(); SynchronousQueue<String> p = new SynchronousQueue<String>(); q.add(tainted); p.add(untainted); String taintedElement = q.poll(); String untaintedElement = p.poll(); taintedElement.toString(); ConnectionManager cm = new ConnectionManager(); cm.publish(untaintedElement); }
public String showFilePicker(String aMimeType) { Intent intent = new Intent(Intent.ACTION_GET_CONTENT); intent.addCategory(Intent.CATEGORY_OPENABLE); intent.setType(aMimeType); GeckoApp.this.startActivityForResult( Intent.createChooser(intent, getString(R.string.choose_file)), FILE_PICKER_REQUEST); String filePickerResult = ""; try { while (null == (filePickerResult = mFilePickerResult.poll(1, TimeUnit.MILLISECONDS))) { Log.i("GeckoApp", "processing events from showFilePicker "); GeckoAppShell.processNextNativeEvent(); } } catch (InterruptedException e) { Log.i(LOG_FILE_NAME, "showing file picker ", e); } return filePickerResult; }
public static void receive(@Observes Response response) throws InterruptedException { RESPONSE_RECEIVED.set(response); SYNCHRONIZER.offer(response, 10, TimeUnit.SECONDS); }
public void deliver(Plate p) throws InterruptedException { // Only blocks if customer is still // eating the previous course: placeSetting.put(p); }
@Override public Task awaitTask() throws InterruptedException { sem.release(); return queue.take(); }