List of usage examples for java.lang Object notify
@HotSpotIntrinsicCandidate public final native void notify();
From source file:net.sf.cindy.impl.ChannelSession.java
protected void onUnregister() { try {/*w ww . ja v a2s . c o m*/ if (readKey != null) { readKey.cancel(); readKey = null; } if (readChannel != null) { readChannel.close(); readChannel = null; } if (writeKey != null) { writeKey.cancel(); writeKey = null; } if (writeChannel != null) { writeChannel.close(); writeChannel = null; } } catch (IOException e) { dispatchException(e); } writeQueue.clear(); synchronized (startLock) { //When block start, will wake up synchronized (closeLock) { //When block close, will wake up synchronized (writeLocks) { for (Iterator iter = writeLocks.iterator(); iter.hasNext();) { Object writeLock = (Object) iter.next(); iter.remove(); synchronized (writeLock) { writeLock.notify(); //When block write, will wake up } } } closing = false; started = false; startLock.notify(); closeLock.notify(); } } dispatchSessionClosed(); }
From source file:it.anyplace.sync.bep.IndexFinder.java
public SearchCompletedEvent doSearch(final String term) throws InterruptedException { final Object lock = new Object(); final AtomicReference<SearchCompletedEvent> reference = new AtomicReference<>(); final Object eventListener = new Object() { @Subscribe/* ww w . j a v a2 s. c o m*/ public void handleSearchCompletedEvent(SearchCompletedEvent event) { if (equal(event.getQuery(), term)) { synchronized (lock) { reference.set(event); lock.notify(); } } } }; synchronized (lock) { eventBus.register(eventListener); submitSearch(term); try { while (!Thread.currentThread().isInterrupted() && reference.get() == null) { lock.wait(); } checkNotNull(reference.get()); return reference.get(); } finally { eventBus.unregister(eventListener); } } }
From source file:it.anyplace.sync.discovery.protocol.ld.LocalDiscorveryHandler.java
public List<DeviceAddress> queryAndClose(final Set<String> deviceIds) { try {/*from ww w . j ava2 s. c om*/ final Object lock = new Object(); synchronized (lock) { eventBus.register(new Object() { @Subscribe public void handleMessageReceivedEvent(MessageReceivedEvent event) { if (deviceIds.contains(event.getDeviceId())) { synchronized (lock) { lock.notify(); } } } }); startListener(); sendAnnounceMessage(); try { lock.wait(MAX_WAIT); } catch (InterruptedException ex) { } synchronized (localDiscoveryRecords) { return Lists.newArrayList(Iterables.concat( Iterables.transform(deviceIds, Functions.forMap(localDiscoveryRecords.asMap())))); } } } finally { close(); } }
From source file:org.mozilla.gecko.tests.testDistribution.java
/** * This is a hack.//from ww w .j a v a 2 s. c o m * * Startup results in us writing prefs -- we fetch the Distribution, which * caches its state. Our tests try to wipe those prefs, but apparently * sometimes race with startup, which leads to us not getting one of our * expected messages. The test fails. * * This hack waits for any existing background tasks -- such as the one that * writes prefs -- to finish before we begin the test. */ private void waitForBackgroundHappiness() { final Object signal = new Object(); final Runnable done = new Runnable() { @Override public void run() { synchronized (signal) { signal.notify(); } } }; synchronized (signal) { ThreadUtils.postToBackgroundThread(done); try { signal.wait(); } catch (InterruptedException e) { mAsserter.ok(false, "InterruptedException waiting on background thread.", e.toString()); } } mAsserter.dumpLog("Background task completed. Proceeding."); }
From source file:com.smartnsoft.hackathon.directenergie.ws.NetatmoServices.java
public synchronized Measures getLastMeasures(String stationId, String moduleId) { final Object synchronizedObject = new Object(); final String[] types = new String[] { Params.TYPE_NOISE, Params.TYPE_CO2, Params.TYPE_PRESSURE, Params.TYPE_HUMIDITY, Params.TYPE_TEMPERATURE }; synchronized (synchronizedObject) { getLastMeasures(stationId, moduleId, Params.SCALE_MAX, types, new NetatmoResponseHandler(this, NetatmoResponseHandler.REQUEST_GET_LAST_MEASURES, types) { @Override//from w ww .j a v a 2 s . co m public void onGetMeasuresResponse(Measures measures) { measuresValue = measures; synchronizedObject.notify(); } @Override public void onFinish() { super.onFinish(); } }); } return measuresValue; }
From source file:org.opennms.netmgt.eventd.adaptors.tcp.TcpStreamHandler.java
/** * The main execution context for processing a remote XML document. Once the * document is processed and an event receipt is returned to the client the * thread will exit.// w w w . java 2s . c o m */ @Override public void run() { // get the context and stop if necessary m_context = Thread.currentThread(); synchronized (m_context) { m_context.notifyAll(); } // check the stop flag if (m_stop) { LOG.debug("The stop flag was set prior to thread entry, closing connection"); try { m_connection.close(); } catch (final IOException e) { LOG.error("An error occured while closing the connection.", e); } LOG.debug("Thread context exiting"); return; } // Log the startup of this stream handler final InetAddress sender = m_connection.getInetAddress(); LOG.debug("Event Log Stream Handler Started for {}", sender); /* * This linked list is used to exchange * instances of PipedOutputStreams. Whenever a * pipe output stream is recovered it must be * signaled to inform the EOT thread of the * ability to write to the pipe. Also, when * the descriptor is close a EOFException is * passed on the list. */ final LinkedList<Object> pipeXchange = new LinkedList<Object>(); final TcpRecordHandler chunker = new TcpRecordHandler(m_connection, pipeXchange); final Thread tchunker = new Thread(chunker, "TCPRecord Chunker[" + InetAddressUtils.str(m_connection.getInetAddress()) + ":" + m_connection.getPort() + "]"); synchronized (tchunker) { tchunker.start(); try { tchunker.wait(); } catch (final InterruptedException e) { LOG.error("The thread was interrupted.", e); } } MAINLOOP: while (!m_stop && m_parent.getStatus() != Fiber.STOP_PENDING && m_parent.getStatus() != Fiber.STOPPED && m_recsPerConn != 0) { // get a new pipe input stream PipedInputStream pipeIn = null; synchronized (pipeXchange) { while (pipeXchange.isEmpty()) { if (chunker.isAlive()) { try { pipeXchange.wait(500); } catch (final InterruptedException e) { LOG.error("The thread was interrupted.", e); break MAINLOOP; } } else { break MAINLOOP; } } // if an exception occured then just exit the BAL (Big Ass Loop) final Object o = pipeXchange.removeFirst(); if (o instanceof Throwable) { break MAINLOOP; } // construct the other end of the pipe try { pipeIn = new PipedInputStream((PipedOutputStream) o); } catch (final IOException e) { LOG.error("An I/O exception occured construction a record reader.", e); break MAINLOOP; } // signal that we got the stream synchronized (o) { o.notify(); } } // decrement the record count if greater than zero m_recsPerConn -= (m_recsPerConn > 0 ? 1 : 0); // convert the pipe input stream into a buffered input stream final InputStream stream = new BufferedInputStream(pipeIn); // Unmarshal the XML document Log eLog = null; boolean doCleanup = false; try { eLog = JaxbUtils.unmarshal(Log.class, new InputSource(stream)); LOG.debug("Event record converted"); } catch (final Exception e) { LOG.error("Could not unmarshall the XML record.", e); doCleanup = true; } finally { if (stream != null) { IOUtils.closeQuietly(stream); } } // clean up the data on the current pipe if necessary if (doCleanup) { /* * Cleanup a failed record. Need to read * the remaining bytes from the other thread * to synchronize up. The other thread might * be blocked writing. */ try { while (stream.read() != -1) { /* do nothing */; } } catch (final IOException e) { // do nothing } // start from the top! continue MAINLOOP; } // Now that we have a list of events, process them final Event[] events = eLog.getEvents().getEvent(); // sort the events by time Arrays.sort(events, new Comparator<Event>() { @Override public int compare(final Event e1, final Event e2) { final boolean e1t = (e1.getTime() != null); final boolean e2t = (e2.getTime() != null); if (e1t && !e2t) { return 1; } else if (!e1t && e2t) { return -1; } else if (!e1t && !e2t) { return 0; } Date de1 = e1.getTime(); Date de2 = e2.getTime(); if (de1 != null && de2 != null) { return (int) (de1.getTime() - de2.getTime()); } else if (de1 == null && de2 != null) { return -1; } else if (de1 != null && de2 == null) { return 1; } else { return 0; } } }); // process the events if (events != null && events.length != 0) { final List<Event> okEvents = new ArrayList<Event>(events.length); /* * This synchronization loop will hold onto the lock * for a while. If the handlers are going to change * often, which is shouldn't then might want to consider * duplicating the handlers into an array before processing * the events. * * Doing the synchronization in the outer loop prevents spending * lots of cycles doing synchronization when it should not * normally be necesary. */ synchronized (m_handlers) { for (final EventHandler hdl : m_handlers) { /* * get the handler and then have it process all * the events in the document before moving to the * next event handler. */ for (final Event event : events) { /* * Process the event and log any errors, * but don't die on these errors */ try { LOG.debug("handling event: {}", event); // shortcut and BOTH parts MUST execute! if (hdl.processEvent(event)) { if (!okEvents.contains(event)) { okEvents.add(event); } } } catch (final Throwable t) { LOG.warn("An exception occured while processing an event.", t); } } } } // Now process the good events and send a receipt message boolean hasReceipt = false; final EventReceipt receipt = new EventReceipt(); for (final Event event : okEvents) { if (event.getUuid() != null) { receipt.addUuid(event.getUuid()); hasReceipt = true; } } if (hasReceipt) { // Transform it to XML and send it to the socket in one call try { final Writer writer = new BufferedWriter( new OutputStreamWriter(m_connection.getOutputStream(), "UTF-8")); JaxbUtils.marshal(receipt, writer); writer.flush(); synchronized (m_handlers) { for (final EventHandler hdl : m_handlers) { /* * Get the handler and then have it process all * the events in the document before moving to * the next event hander. */ try { hdl.receiptSent(receipt); } catch (final Throwable t) { LOG.warn("An exception occured while processing an event receipt.", t); } } } if (LOG.isDebugEnabled()) { try { final StringWriter swriter = new StringWriter(); JaxbUtils.marshal(receipt, swriter); LOG.debug("Sent Event Receipt {"); LOG.debug(swriter.getBuffer().toString()); LOG.debug("}"); } catch (final Throwable e) { LOG.error("An error occured during marshalling of event receipt for the log.", e); } } } catch (final IOException e) { LOG.warn("Failed to send event-receipt XML document.", e); break MAINLOOP; } } } else { LOG.debug("The agent sent an empty event stream"); } } try { LOG.debug("stopping record handler"); chunker.stop(); LOG.debug("record handler stopped"); } catch (final InterruptedException e) { LOG.warn("The thread was interrupted while trying to close the record handler.", e); } // regardless of any errors, be sure to release the socket. try { LOG.debug("closing connnection"); m_connection.close(); LOG.debug("connnection closed "); } catch (final IOException e) { LOG.warn("An I/O exception occured while closing the TCP/IP connection.", e); } LOG.debug("Thread exiting"); }
From source file:it.anyplace.sync.bep.BlockPuller.java
public FileDownloadObserver pullBlocks(FileBlocks fileBlocks) throws InterruptedException { logger.info("pulling file = {}", fileBlocks); checkArgument(connectionHandler.hasFolder(fileBlocks.getFolder()), "supplied connection handler %s will not share folder %s", connectionHandler, fileBlocks.getFolder());/*from w ww .j ava 2s. c o m*/ final Object lock = new Object(); final AtomicReference<Exception> error = new AtomicReference<>(); final Object listener = new Object() { @Subscribe public void handleResponseMessageReceivedEvent(ResponseMessageReceivedEvent event) { synchronized (lock) { try { if (!requestIds.contains(event.getMessage().getId())) { return; } checkArgument(equal(event.getMessage().getCode(), ErrorCode.NO_ERROR), "received error response, code = %s", event.getMessage().getCode()); byte[] data = event.getMessage().getData().toByteArray(); String hash = BaseEncoding.base16().encode(Hashing.sha256().hashBytes(data).asBytes()); blockCache.pushBlock(data); if (missingHashes.remove(hash)) { blocksByHash.put(hash, data); logger.debug("aquired block, hash = {}", hash); lock.notify(); } else { logger.warn("received not-needed block, hash = {}", hash); } } catch (Exception ex) { error.set(ex); lock.notify(); } } } }; FileDownloadObserver fileDownloadObserver = new FileDownloadObserver() { private long getReceivedData() { return blocksByHash.size() * BLOCK_SIZE; } private long getTotalData() { return (blocksByHash.size() + missingHashes.size()) * BLOCK_SIZE; } @Override public double getProgress() { return isCompleted() ? 1d : getReceivedData() / ((double) getTotalData()); } @Override public String getProgressMessage() { return (Math.round(getProgress() * 1000d) / 10d) + "% " + FileUtils.byteCountToDisplaySize(getReceivedData()) + " / " + FileUtils.byteCountToDisplaySize(getTotalData()); } @Override public boolean isCompleted() { return missingHashes.isEmpty(); } @Override public void checkError() { if (error.get() != null) { throw new RuntimeException(error.get()); } } @Override public double waitForProgressUpdate() throws InterruptedException { if (!isCompleted()) { synchronized (lock) { checkError(); lock.wait(); checkError(); } } return getProgress(); } @Override public InputStream getInputStream() { checkArgument(missingHashes.isEmpty(), "pull failed, some blocks are still missing"); List<byte[]> blockList = Lists .newArrayList(Lists.transform(hashList, Functions.forMap(blocksByHash))); return new SequenceInputStream(Collections .enumeration(Lists.transform(blockList, new Function<byte[], ByteArrayInputStream>() { @Override public ByteArrayInputStream apply(byte[] data) { return new ByteArrayInputStream(data); } }))); } @Override public void close() { missingHashes.clear(); hashList.clear(); blocksByHash.clear(); try { connectionHandler.getEventBus().unregister(listener); } catch (Exception ex) { } if (closeConnection) { connectionHandler.close(); } } }; try { synchronized (lock) { hashList.addAll(Lists.transform(fileBlocks.getBlocks(), new Function<BlockInfo, String>() { @Override public String apply(BlockInfo block) { return block.getHash(); } })); missingHashes.addAll(hashList); for (String hash : missingHashes) { byte[] block = blockCache.pullBlock(hash); if (block != null) { blocksByHash.put(hash, block); missingHashes.remove(hash); } } connectionHandler.getEventBus().register(listener); for (BlockInfo block : fileBlocks.getBlocks()) { if (missingHashes.contains(block.getHash())) { int requestId = Math.abs(new Random().nextInt()); requestIds.add(requestId); connectionHandler.sendMessage(Request.newBuilder().setId(requestId) .setFolder(fileBlocks.getFolder()).setName(fileBlocks.getPath()) .setOffset(block.getOffset()).setSize(block.getSize()) .setHash(ByteString.copyFrom(BaseEncoding.base16().decode(block.getHash()))) .build()); logger.debug("sent request for block, hash = {}", block.getHash()); } } return fileDownloadObserver; } } catch (Exception ex) { fileDownloadObserver.close(); throw ex; } }
From source file:org.apache.stratos.integration.common.TopologyHandler.java
/** * Assert application Inactive status//from w w w. j av a2 s . c o m * * @param applicationId * @param timeout */ public void assertApplicationInActiveStatus(final String applicationId, final int timeout) throws InterruptedException { log.info(String.format( "Asserting application status INACTIVE for [application-id] %s within [timeout] %d ms...", applicationId, timeout)); final long startTime = System.currentTimeMillis(); final Object synObject = new Object(); ApplicationInstanceInactivatedEventListener inactivatedEventListener = new ApplicationInstanceInactivatedEventListener() { @Override protected void onEvent(Event event) { Application application = ApplicationManager.getApplications().getApplication(applicationId); if (application == null || application.getStatus() == ApplicationStatus.Inactive) { synchronized (synObject) { synObject.notify(); } } } }; applicationsEventReceiver.addEventListener(inactivatedEventListener); Future future = executorService.submit(new Runnable() { @Override public void run() { Application application = ApplicationManager.getApplications().getApplication(applicationId); while (!((application != null) && (application.getStatus() == ApplicationStatus.Inactive))) { if ((System.currentTimeMillis() - startTime) > timeout) { log.error(String.format( "Application [application-id] %s did not become inactive within [timeout] %d", applicationId, timeout)); break; } ApplicationStatus currentStatus = (application != null) ? application.getStatus() : null; log.info(String.format( "Waiting for [application-id] %s [current-status] %s to become [status] %s...", applicationId, currentStatus, ApplicationStatus.Inactive)); sleep(10000); application = ApplicationManager.getApplications().getApplication(applicationId); } synchronized (synObject) { synObject.notify(); } } }); synchronized (synObject) { synObject.wait(); future.cancel(true); applicationsEventReceiver.removeEventListener(inactivatedEventListener); } Application application = ApplicationManager.getApplications().getApplication(applicationId); ApplicationStatus currentStatus = (application != null) ? application.getStatus() : null; log.info(String.format( "Assert application inactive status for [application-id] %s [current-status] %s took %d ms", applicationId, currentStatus, System.currentTimeMillis() - startTime)); assertNotNull(String.format("Application is not found: [application-id] %s", applicationId), application); assertEquals( String.format("Application status did not change to %s: [application-id] %s", ApplicationStatus.Inactive, applicationId), ApplicationStatus.Inactive, application.getStatus()); }
From source file:org.apache.stratos.integration.common.TopologyHandler.java
/** * Assert application Active status/*from w w w . j a v a 2 s . c om*/ * * @param applicationId */ public void assertApplicationActiveStatus(final String applicationId) throws InterruptedException { log.info(String.format("Asserting application status ACTIVE for [application-id] %s...", applicationId)); final long startTime = System.currentTimeMillis(); final Object synObject = new Object(); ApplicationInstanceActivatedEventListener activatedEventListener = new ApplicationInstanceActivatedEventListener() { @Override protected void onEvent(Event event) { ApplicationInstanceActivatedEvent activatedEvent = (ApplicationInstanceActivatedEvent) event; Application application = ApplicationManager.getApplications().getApplication(applicationId); if (application == null) { log.warn(String.format("Application is null: [application-id] %s, [instance-id] %s", applicationId, activatedEvent.getInstanceId())); } if (application != null && application.getStatus() == ApplicationStatus.Active) { synchronized (synObject) { synObject.notify(); } } } }; applicationsEventReceiver.addEventListener(activatedEventListener); Future future = executorService.submit(new Runnable() { @Override public void run() { Application application = ApplicationManager.getApplications().getApplication(applicationId); while (!((application != null) && (application.getStatus() == ApplicationStatus.Active))) { if ((System.currentTimeMillis() - startTime) > APPLICATION_ACTIVATION_TIMEOUT) { log.error(String.format( "Application [application-id] %s did not activate within [timeout] %d", applicationId, APPLICATION_ACTIVATION_TIMEOUT)); break; } ApplicationStatus currentStatus = (application != null) ? application.getStatus() : null; log.info(String.format( "Waiting for [application-id] %s [current-status] %s to become [status] %s...", applicationId, currentStatus, ApplicationStatus.Active)); sleep(10000); application = ApplicationManager.getApplications().getApplication(applicationId); } synchronized (synObject) { synObject.notify(); } } }); synchronized (synObject) { synObject.wait(); future.cancel(true); applicationsEventReceiver.removeEventListener(activatedEventListener); } Application application = ApplicationManager.getApplications().getApplication(applicationId); ApplicationStatus currentStatus = (application != null) ? application.getStatus() : null; log.info(String.format( "Assert application active status for [application-id] %s [current-status] %s took %d ms", applicationId, currentStatus, System.currentTimeMillis() - startTime)); assertNotNull(String.format("Application is not found: [application-id] %s", applicationId), application); assertEquals( String.format("Application status did not change to %s: [application-id] %s", ApplicationStatus.Active, applicationId), ApplicationStatus.Active, application.getStatus()); }
From source file:com.meltmedia.cadmium.servlets.ClassLoaderLeakPreventor.java
protected void stopTimerThread(Thread thread) { // Seems it is not possible to access Timer of TimerThread, so we need to mimic Timer.cancel() /**// w w w. j ava 2 s.c o m try { Timer timer = (Timer) findField(thread.getClass(), "this$0").get(thread); // This does not work! warn("Cancelling Timer " + timer + " / TimeThread '" + thread + "'"); timer.cancel(); } catch (IllegalAccessException iaex) { error(iaex); } */ try { final Field newTasksMayBeScheduled = findField(thread.getClass(), "newTasksMayBeScheduled"); final Object queue = findField(thread.getClass(), "queue").get(thread); // java.lang.TaskQueue final Method clear = queue.getClass().getDeclaredMethod("clear"); clear.setAccessible(true); // Do what java.util.Timer.cancel() does //noinspection SynchronizationOnLocalVariableOrMethodParameter synchronized (queue) { newTasksMayBeScheduled.set(thread, false); clear.invoke(queue); queue.notify(); // "In case queue was already empty." } // We shouldn't need to join() here, thread will finish soon enough } catch (Exception ex) { error(ex); } }