private void drinking() { if (!Thread.holdsLock(left) || !Thread.holdsLock(right)) { throw new IllegalMonitorStateException("Not holding both locks"); } System.out.printf("(%d) Drinking%n", id); drinks++; }
{ assertFalse(Thread.holdsLock(mSync)); synchronized (mSync) { assertTrue(Thread.holdsLock(mSync)); } assertFalse(Thread.holdsLock(mSync)); }
void receiveHeaders(List<String> headers, HeadersMode headersMode) { assert (!Thread.holdsLock(SpdyStream.this)); ErrorCode errorCode = null; boolean open = true; synchronized (this) { if (responseHeaders == null) { if (headersMode.failIfHeadersAbsent()) { errorCode = ErrorCode.PROTOCOL_ERROR; } else { responseHeaders = headers; open = isOpen(); notifyAll(); } } else { if (headersMode.failIfHeadersPresent()) { errorCode = ErrorCode.STREAM_IN_USE; } else { List<String> newHeaders = new ArrayList<String>(); newHeaders.addAll(responseHeaders); newHeaders.addAll(headers); this.responseHeaders = newHeaders; } } } if (errorCode != null) { closeLater(errorCode); } else if (!open) { connection.removeStream(id); } }
@Override public boolean execute(ManagedServer server) throws Exception { assert Thread.holdsLock(ManagedServer.this); // Call under lock // Stop process try { // graceful shutdown // this just suspends the server, it does not actually shut it down if (permit != -1) { final ModelNode operation = new ModelNode(); operation.get(OP).set("shutdown"); operation.get(OP_ADDR).setEmptyList(); operation.get("operation-id").set(permit); operation.get("timeout").set(timeout); final TransactionalProtocolClient.PreparedOperation<?> prepared = TransactionalProtocolHandlers.executeBlocking(operation, protocolClient); if (prepared.isFailed()) { return true; } // we stop the server via an operation prepared.commit(); prepared.getFinalResult().get(); } } catch (Exception ignore) { } finally { try { processControllerClient.stopProcess(serverProcessName); } catch (IOException ignore) { } } return true; }
@Override public boolean execute(ManagedServer server) throws Exception { assert Thread.holdsLock(ManagedServer.this); // Call under lock // Start the process processControllerClient.startProcess(serverProcessName); return true; }
private boolean internalSetState( final TransitionTask task, final InternalState current, final InternalState next) { assert Thread.holdsLock(this); // Call under lock final InternalState internalState = this.internalState; ROOT_LOGGER.logf( DEBUG_LEVEL, "changing server state (%s) from %s to %s", serverName, current, next); if (internalState == current) { try { if (task != null) { if (!task.execute(this)) { return true; // Not a failure condition } } this.internalState = next; return true; } catch (final Exception e) { ROOT_LOGGER.logf( DEBUG_LEVEL, e, "transition (%s > %s) failed for server \"%s\"", current, next, serverName); transitionFailed(current, e); } finally { notifyAll(); } } return false; }
private void addLineDef(@Nonnull final PlotLineDef toBeAdded) { if (!Thread.holdsLock(this)) throw new AssertionError(); List<PlotLineDef> registeredLineDefs = registeredLineDefsMap.get(toBeAdded); if (registeredLineDefs == null) { registeredLineDefs = new ArrayList<PlotLineDef>(); registeredLineDefsMap.put(toBeAdded, registeredLineDefs); } try { Iterables.find( registeredLineDefs, new Predicate<PlotLineDef>() { @Override public boolean apply(@Nullable PlotLineDef lineDef) { return lineDef == toBeAdded; } }); // already added } catch (NoSuchElementException e) { registeredLineDefs.add(toBeAdded); } }
private boolean closeInternal(ErrorCode errorcode) { if (!$assertionsDisabled && Thread.holdsLock(this)) { throw new AssertionError(); } this; JVM INSTR monitorenter ; if (errorCode == null) { break MISSING_BLOCK_LABEL_34; } this; JVM INSTR monitorexit ; return false; if (!source.finished || !sink.finished) { break MISSING_BLOCK_LABEL_63; } this; JVM INSTR monitorexit ; return false; errorcode; this; JVM INSTR monitorexit ; throw errorcode; errorCode = errorcode; notifyAll(); this; JVM INSTR monitorexit ; connection.removeStream(id); return true; }
/** * @param nodeId Node ID. * @return Class loader ID for node ID. */ GridTuple2<GridUuid, Long> getClassLoaderId(UUID nodeId) { assert nodeId != null; assert Thread.holdsLock(mux); return loader().registeredClassLoaderId(nodeId); }
@Override public void addSources(List<TaskSource> sources) { checkNotNull(sources, "sources is null"); checkState( !Thread.holdsLock(this), "Can not add sources while holding a lock on the %s", getClass().getSimpleName()); try (SetThreadName setThreadName = new SetThreadName("Task-%s", taskId)) { // update our record of sources and schedule drivers for new partitioned splits Map<PlanNodeId, TaskSource> updatedUnpartitionedSources = updateSources(sources); // tell existing drivers about the new splits; it is safe to update drivers // multiple times and out of order because sources contain full record of // the unpartitioned splits for (TaskSource source : updatedUnpartitionedSources.values()) { // tell all the existing drivers this source is finished for (WeakReference<Driver> driverReference : drivers) { Driver driver = driverReference.get(); // the driver can be GCed due to a failure or a limit if (driver != null) { driver.updateSource(source); } else { // remove the weak reference from the list to avoid a memory leak // NOTE: this is a concurrent safe operation on a CopyOnWriteArrayList drivers.remove(driverReference); } } } } }
/** * Adds a geographic CRS from the specified parameters. * * @param code The CRS code. * @param name The CRS and datum name. * @param ellipsoid The ellipsoid. * @throws FactoryException if factories failed to creates the CRS. */ private void add(final int code, final String name, final Ellipsoid ellipsoid) throws FactoryException { assert Thread.holdsLock(this); final Map properties = new HashMap(); final Citation authority = getAuthority(); final String text = String.valueOf(code); properties.put(IdentifiedObject.NAME_KEY, name); properties.put(Identifier.AUTHORITY_KEY, authority); final GeodeticDatum datum = factories .getDatumFactory() .createGeodeticDatum(properties, ellipsoid, DefaultPrimeMeridian.GREENWICH); properties.put( IdentifiedObject.IDENTIFIERS_KEY, new NamedIdentifier[] { new NamedIdentifier(authority, text), new NamedIdentifier(authority, PREFIX + text) }); final CoordinateReferenceSystem crs = factories .getCRSFactory() .createGeographicCRS(properties, datum, DefaultEllipsoidalCS.GEODETIC_2D); if (crsMap.put(code, crs) != null) { throw new IllegalArgumentException(text); } }
// @synchronization caller must have sync on fileSync !!! protected DecimatedStake allocAsync(Span span) throws IOException { if (!Thread.holdsLock(fileSync)) throw new IllegalMonitorStateException(); final long floorStart = span.start & MAXMASK; final long ceilStop = (span.stop + MAXCEILADD) & MAXMASK; final Span extSpan = (floorStart == span.start) && (ceilStop == span.stop) ? span : new Span(floorStart, ceilStop); final Span[] fileSpans = new Span[SUBNUM]; final Span[] biasedSpans = new Span[SUBNUM]; long fileStart; long fileStop; if (tempFAsync == null) { // XXX THIS IS THE PLACE TO OPEN WAVEFORM CACHE FILE tempFAsync = createTempFiles(); } synchronized (tempFAsync) { for (int i = 0; i < SUBNUM; i++) { fileStart = tempFAsync[i].getFrameNum(); fileStop = fileStart + (extSpan.getLength() >> decimHelps[i].shift); tempFAsync[i].setFrameNum(fileStop); fileSpans[i] = new Span(fileStart, fileStop); biasedSpans[i] = extSpan; } } return new DecimatedStake(extSpan, tempFAsync, fileSpans, biasedSpans, decimHelps); }
private void releaseEncryptedOutputBuffer() { if (!Thread.holdsLock(DecryptedEndPoint.this)) throw new IllegalStateException(); if (_encryptedOutput != null && !_encryptedOutput.hasRemaining()) { _bufferPool.release(_encryptedOutput); _encryptedOutput = null; } }
public void runReadAction(@NotNull final Runnable action) { /** * if we are inside read action, do not try to acquire read lock again since it will deadlock if * there is a pending writeAction see {@link * com.intellij.util.concurrency.ReentrantWriterPreferenceReadWriteLock#allowReader()} */ if (isReadAccessAllowed()) { action.run(); return; } LOG.assertTrue( !Thread.holdsLock(PsiLock.LOCK), "Thread must not hold PsiLock while performing readAction"); try { myActionsLock.readLock().acquire(); } catch (InterruptedException e) { throw new RuntimeInterruptedException(e); } try { action.run(); } finally { myActionsLock.readLock().release(); } }
public boolean tryRunReadAction(@NotNull Runnable action) { /** * if we are inside read action, do not try to acquire read lock again since it will deadlock if * there is a pending writeAction see {@link * com.intellij.util.concurrency.ReentrantWriterPreferenceReadWriteLock#allowReader()} */ boolean mustAcquire = !isReadAccessAllowed(); if (mustAcquire) { LOG.assertTrue( myTestModeFlag || !Thread.holdsLock(PsiLock.LOCK), "Thread must not hold PsiLock while performing readAction"); try { if (!myActionsLock.readLock().attempt(0)) return false; } catch (InterruptedException e) { throw new RuntimeInterruptedException(e); } } try { action.run(); } finally { if (mustAcquire) { myActionsLock.readLock().release(); } } return true; }
/** * Try to load a config XML file from a named path. If the file does not exist, return * NONEXISTENT; or if there is any load error, return null. */ private Document loadXml(String path) { assert ProjectManager.mutex().isReadAccess() || ProjectManager.mutex().isWriteAccess(); assert Thread.holdsLock(modifiedMetadataPaths); FileObject xml = dir.getFileObject(path); if (xml == null || !xml.isData()) { return NONEXISTENT; } try { Document doc = XMLUtil.parse( new InputSource(xml.getInputStream()), false, true, XMLUtil.defaultErrorHandler(), null); return doc; } catch (IOException e) { if (!QUIETLY_SWALLOW_XML_LOAD_ERRORS) { LOG.log(Level.INFO, "Load XML: {0}", xml.getPath()); // NOI18N ErrorManager.getDefault().notify(ErrorManager.INFORMATIONAL, e); } } catch (SAXException e) { if (!QUIETLY_SWALLOW_XML_LOAD_ERRORS) { LOG.log(Level.INFO, "Load XML: {0}", xml.getPath()); // NOI18N ErrorManager.getDefault().notify(ErrorManager.INFORMATIONAL, e); } } return null; }
private boolean startProcessing() { LOG.assertTrue(Thread.holdsLock(myQueue)); if (isProcessing || !myStarted) { return false; } isProcessing = true; final T item = myQueue.removeFirst(); final Runnable runnable = () -> { if (myDeathCondition.value(null)) return; runSafely(() -> myProcessor.consume(item, myContinuationContext)); }; final Application application = ApplicationManager.getApplication(); if (myThreadToUse == ThreadToUse.AWT) { final ModalityState state = myModalityState.remove(new MyOverrideEquals(item)); if (state != null) { application.invokeLater(runnable, state); } else { application.invokeLater(runnable); } } else { application.executeOnPooledThread(runnable); } return true; }
/** {@inheritDoc} */ protected void getNewMonitors(Map<String, Monitor> map) throws MonitorException { assert Thread.holdsLock(this); int used = prologue.getUsed(); long modificationTime = prologue.getModificationTimeStamp(); if ((used > lastUsed) || (lastModificationTime > modificationTime)) { lastUsed = used; lastModificationTime = modificationTime; Monitor monitor = getNextMonitorEntry(); while (monitor != null) { String name = monitor.getName(); // guard against duplicate entries if (!map.containsKey(name)) { map.put(name, monitor); /* * insertedMonitors is null when called from pollFor() * via buildMonitorMap(). Since we update insertedMonitors * at the end of buildMonitorMap(), it's ok to skip the * add here. */ if (insertedMonitors != null) { insertedMonitors.add(monitor); } } monitor = getNextMonitorEntry(); } } }
public void reply(List<Header> paramList, boolean paramBoolean) throws IOException { assert (!Thread.holdsLock(this)); boolean bool = false; if (paramList == null) { try { throw new NullPointerException("responseHeaders == null"); } finally {} } if (this.responseHeaders != null) { throw new IllegalStateException("reply already sent"); } this.responseHeaders = paramList; if (!paramBoolean) { SpdyDataSink.access$202(this.sink, true); bool = true; } this.connection.writeSynReply(this.id, bool, paramList); if (bool) { this.connection.flush(); } }
public BufferResult getPages(long startingSequenceId, DataSize maxSize) { Preconditions.checkState( Thread.holdsLock(SharedBuffer.this), "Thread must hold a lock on the %s", SharedBuffer.class.getSimpleName()); Preconditions.checkArgument(maxSize.toBytes() > 0, "maxSize must be at least 1 byte"); acknowledge(startingSequenceId); if (finished) { return emptyResults(sequenceId, true); } int listOffset = Ints.checkedCast(sequenceId - masterSequenceId); if (listOffset >= masterQueue.size()) { return emptyResults(sequenceId, false); } long maxBytes = maxSize.toBytes(); List<Page> pages = new ArrayList<>(); long bytes = 0; while (listOffset < masterQueue.size()) { Page page = masterQueue.get(listOffset++); bytes += page.getDataSize().toBytes(); // break (and don't add) if this page would exceed the limit if (!pages.isEmpty() && bytes > maxBytes) { break; } pages.add(page); } return new BufferResult(startingSequenceId, false, ImmutableList.copyOf(pages)); }
void receive(InputStream in, int byteCount) throws IOException { assert (!Thread.holdsLock(SpdyStream.this)); if (byteCount == 0) { return; } int pos; int limit; int firstNewByte; boolean finished; boolean flowControlError; synchronized (SpdyStream.this) { finished = this.finished; pos = this.pos; firstNewByte = this.limit; limit = this.limit; flowControlError = byteCount > buffer.length - available(); } // If the peer sends more data than we can handle, discard it and close the connection. if (flowControlError) { Util.skipByReading(in, byteCount); closeLater(ErrorCode.FLOW_CONTROL_ERROR); return; } // Discard data received after the stream is finished. It's probably a benign race. if (finished) { Util.skipByReading(in, byteCount); return; } // Fill the buffer without holding any locks. First fill [limit..buffer.length) if that // won't overwrite unread data. Then fill [limit..pos). We can't hold a lock, otherwise // writes will be blocked until reads complete. if (pos < limit) { int firstCopyCount = Math.min(byteCount, buffer.length - limit); Util.readFully(in, buffer, limit, firstCopyCount); limit += firstCopyCount; byteCount -= firstCopyCount; if (limit == buffer.length) { limit = 0; } } if (byteCount > 0) { Util.readFully(in, buffer, limit, byteCount); limit += byteCount; } synchronized (SpdyStream.this) { // Update the new limit, and mark the position as readable if necessary. this.limit = limit; if (this.pos == -1) { this.pos = firstNewByte; SpdyStream.this.notifyAll(); } } }
/** * Checks if node is participating in deployment. * * @param nodeId Node ID to check. * @param ldrId Class loader ID. * @return {@code True} if node is participating in deployment. */ boolean hasParticipant(UUID nodeId, GridUuid ldrId) { assert nodeId != null; assert ldrId != null; assert Thread.holdsLock(mux); return loader().hasRegisteredNode(nodeId, ldrId); }
public boolean isFinished() { Preconditions.checkState( Thread.holdsLock(SharedBuffer.this), "Thread must hold a lock on the %s", SharedBuffer.class.getSimpleName()); return finished; }
public void setFinished() { Preconditions.checkState( Thread.holdsLock(SharedBuffer.this), "Thread must hold a lock on the %s", SharedBuffer.class.getSimpleName()); finished = true; }
public long getSequenceId() { Preconditions.checkState( Thread.holdsLock(SharedBuffer.this), "Thread must hold a lock on the %s", SharedBuffer.class.getSimpleName()); return sequenceId; }
/** Resets the connection state so that the client can connect and login again. */ private void reset() { assert Thread.holdsLock(lock); connected = false; connection = null; loginAck = false; loginSuccess = false; loginRedirect = false; }
/** * If the context is committed, flushes channel tasks (enqueued during this transaction) to the * task handler's map, notifies the task handler that there are tasks to process, and returns * true; otherwise returns false. */ private boolean flush() { assert Thread.holdsLock(contextList); if (isCommitted) { for (BigInteger channelId : internalTaskLists.keySet()) { flushTasks(channelId, internalTaskLists.get(channelId)); } } return isCommitted; }
private void setSettings(Settings settings) { // TODO: For HTTP/2.0, also adjust the stream flow control window size // by the difference between the new value and the old value. assert (Thread.holdsLock(connection)); // Because 'settings' is guarded by 'connection'. this.writeWindowSize = settings != null ? settings.getInitialWindowSize(Settings.DEFAULT_INITIAL_WINDOW_SIZE) : Settings.DEFAULT_INITIAL_WINDOW_SIZE; }
@Override public void flush() throws IOException { assert (!Thread.holdsLock(SpdyStream.this)); checkNotClosed(); if (pos > 0) { writeFrame(false); connection.flush(); } }
/** * Returns the service registry. The registry will be created the first time this method is * invoked. */ private static FactoryRegistry getServiceRegistry() { assert Thread.holdsLock(CoverageFactoryFinder.class); if (registry == null) { registry = new DynamicFactoryRegistry( Arrays.asList( new Class<?>[] {GridCoverageFactory.class, GridCoverageProcessor.class})); } return registry; }