NOT SYNCHRONIZED! Call within constructor or from synch'd method.
176210
int putSymbol(String symbolName)
    {

        if (isReadOnly)
        {
            throw new ReadOnlyValueException(SymbolTable.class);
        }

        if (mySymbolsCount == mySymbolNames.length)
        {
            int newlen = mySymbolsCount * 2;
            if (newlen < DEFAULT_CAPACITY)
            {
                newlen = DEFAULT_CAPACITY;
            }
            String[] temp = new String[newlen];
            System.arraycopy(mySymbolNames, 0, temp, 0, mySymbolsCount);
            mySymbolNames = temp;
        }

        int sid = -1;
        if (symbolName != null)
        {
            sid = mySymbolsCount + myFirstLocalSid;
            assert sid == getMaxId() + 1;

            putToMapIfNotThere(mySymbolsMap, symbolName, sid);
        }
        mySymbolNames[mySymbolsCount] = symbolName;
        mySymbolsCount++;

        return sid;
    }
1311356
def call_sync(func):
    """"""

    @wraps(func)
    def wrapper(self, *args, **kw):
        """Wraps instance method to be called on loop thread"""

        # Just return when already on the event thread
        if self.thread.ident == get_ident():
            return func(self, *args, **kw)

        barrier = Barrier(2)
        result = None
        ex = None

        def call():
            """Calls function on loop thread"""
            nonlocal result, ex
            try:
                result = func(self, *args, **kw)
            except Exception as exc:
                ex = exc
            finally:
                barrier.wait()

        self.loop.call_soon_threadsafe(call)
        barrier.wait()
        if ex:
            raise ex or Exception("Unknown error")
        return result

    return wrapper
34368
private static boolean isAsyncMethod(Method method) {
        Class<?>[] parameterTypes = method.getParameterTypes();
        for (Class<?> c : parameterTypes)
        {
            if (c.isAssignableFrom(javax.ws.rs.container.AsyncResponse.class))
                return true;
        }
        return false;
    }
528317
function(syncIt) {
	/* global setInterval */
	this._syncIt = syncIt;
	this._instructions = [];
	this._current = null;
	setInterval(function() {
		var args, c;
		if ((this._current === null) && this._instructions.length) {
			this._current = this._instructions.shift();
			args = Array.prototype.slice.call(this._current.a);
			args.push(function(e) {
				if (e !== SyncItConstant.Error.UNABLE_TO_PROCESS_BECAUSE_LOCKED) {
					c = this._current.c;
					this._current = null;
					c.apply(
						this._syncIt,
						arguments
					);
				}
			}.bind(this));
			this._current.f.apply(this._syncIt, args);
		}
	}.bind(this), 50);
}
378788
@Override
    public void visitClassContext(ClassContext classContext) {
        try {
            JavaClass cls = classContext.getJavaClass();
            if (isSingleton(cls)) {
                syncBlockBranchResetValues = new HashMap<>();
                stack = new OpcodeStack();
                super.visitClassContext(classContext);
            }
        } finally {
            syncBlockBranchResetValues = null;
            stack = null;
        }
    }
206316
@SuppressWarnings("unchecked")
	private void privateSync(final boolean syncInternal, final boolean forceSyncStore) {
		if (readOnly) {
			return;
		}
		final long ts = System.currentTimeMillis();
		boolean isDirty = false;
		if (!dirtyLeafNodes.isEmpty() || !dirtyInternalNodes.isEmpty()) {
			submitRedoMeta(0); // Meta Sync (full recover needed)
		}
		//
		// Write Leaf Nodes
		if (!dirtyLeafNodes.isEmpty()) {
			isDirty = true;
			final Node<K, V>[] dirtyBlocks = dirtyLeafNodes.getValues();
			Arrays.sort(dirtyBlocks, dirtyComparatorByID);
			for (Node<K, V> node : dirtyBlocks) {
				if (node == null) {
					break;
				}
				// if (log.isDebugEnabled()) log.debug("node.id=" + node.id);
				dirtyLeafNodes.remove(node.id);
				putNodeToStore(node);
				if (!node.isDeleted()) {
					cacheLeafNodes.put(node.id, node);
				}
			}
			if (!dirtyLeafNodes.isEmpty()) {
				dirtyLeafNodes.clear(false); // Clear without shrink
			}
		}
		// Write Internal Nodes
		if (syncInternal && !dirtyInternalNodes.isEmpty()) {
			isDirty = true;
			final Node<K, V>[] dirtyBlocks = dirtyInternalNodes.getValues();
			Arrays.sort(dirtyBlocks, dirtyComparatorByID);
			for (Node<K, V> node : dirtyBlocks) {
				if (node == null) {
					break;
				}
				// if (log.isDebugEnabled()) log.debug("node.id=" + node.id);
				dirtyInternalNodes.remove(node.id);
				putNodeToStore(node);
				if (!node.isDeleted()) {
					cacheInternalNodes.put(node.id, node);
				}
			}
			if (!dirtyInternalNodes.isEmpty()) {
				dirtyInternalNodes.clear(false); // Clear without shrink
			}
		}
		//
		if (isDirty) {
			writeMetaData(false);
			if (forceSyncStore || !disableAutoSyncStore)
				storage.sync();
			redoQueue.clear();
			redoStore.clear();
		}
		if (log.isDebugEnabled()) {
			final StringBuilder sb = new StringBuilder();
			// @formatter:off
			sb
			.append(this.getClass().getName()).append("::sync()")
			.append(" elements=").append(elements)
			.append(" Int=").append(maxInternalNodes)
			.append(" Leaf=").append(maxLeafNodes)
			.append(" dirty{")
			.append(" Int=").append(dirtyInternalNodes.size())
			.append(" Leaf=").append(dirtyLeafNodes.size())
			.append(" }")
			.append(" cache{")
			.append(" Int=").append(cacheInternalNodes.size())
			.append(" Leaf=").append(cacheLeafNodes.size())
			.append(" }")
			.append(" storage{")
			.append(" total=").append(storage.sizeInBlocks())
			.append(" free=").append(freeBlocks.cardinality())
			.append(" }")
			.append(" time=").append(System.currentTimeMillis() - ts);
			// @formatter:on
			log.debug(sb.toString());
		}
		// clearWriteCaches();
	}
13345
private void invalidateSync() {
        Log.d("AndroidClockSync", "Starting sync...");
        new Thread() {
            @Override
            public void run() {
                SntpClient client = new SntpClient();
                ExponentialBackoff exponentialBackoff = new ExponentialBackoff();
                while (!client.requestTime(serverHost, 10000)) {
                    exponentialBackoff.onFailure();
                    try {
                        Thread.sleep(exponentialBackoff.exponentialWait());
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
                syncDelta = client.getClockOffset();
                preference.edit().putLong("delta", syncDelta).commit();
                Log.d("AndroidClockSync", "Synced. Time delta: " + syncDelta + " ms");
            }
        }.start();
    }
1056700
@Override
    public boolean addSync() throws ResourceException {
        if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) {
            Tr.debug(tc, hexId() + ":addSynch()");
        }
        return false;
    }
1027300
public final void unblock() {
		if (Threading.debugSynchronization) ThreadingDebugHelper.unblocked(this);
		ArrayList<Runnable> listeners;
		synchronized (this) {
			if (unblocked) return;
			unblocked = true;
			if (listenersInline == null) {
				this.notifyAll();
				return;
			}
			listeners = listenersInline;
			listenersInline = new ArrayList<>(2);
		}
		Logger log = LCCore.getApplication().getLoggerFactory().getLogger(SynchronizationPoint.class);
		while (true) {
			if (!log.debug())
				for (int i = 0; i < listeners.size(); ++i)
					try { listeners.get(i).run(); }
					catch (Throwable t) { log.error(
						"Exception thrown by an inline listener of SynchronizationPoint", t); }
			else
				for (int i = 0; i < listeners.size(); ++i) {
					long start = System.nanoTime();
					try { listeners.get(i).run(); }
					catch (Throwable t) { log.error(
						"Exception thrown by an inline listener of SynchronizationPoint", t); }
					long time = System.nanoTime() - start;
					if (time > 1000000) // more than 1ms
						log.debug("Listener took " + (time / 1000000.0d) + "ms: " + listeners.get(i));
				}
			synchronized (this) {
				if (listenersInline.isEmpty()) {
					listenersInline = null;
					listeners = null;
					this.notifyAll();
					break;
				}
				listeners.clear();
				ArrayList<Runnable> tmp = listeners;
				listeners = listenersInline;
				listenersInline = tmp;
			}
		}
	}
678015
def execute(receiver, method, args, block)
      @mutex.synchronize do
        raise "already calling" if @call
        @call = Call::Sync.new(self, method, args, block)
      end

      receiver << @call
    end
370263
public void synchronize(List<? extends E> list) {
		assert SwingUtilities.isEventDispatchThread() : ApplicationResources.accessor.getMessage("assert.notRunningInSwingEventThread");

		// Make sure the first element exists and matches
		int modelOffset;
		if(constantFirstRow!=null) {
			modelOffset = 1;
			if(getSize()==0) addElement(constantFirstRow);
			else if(!getElementAt(0).equals(constantFirstRow)) {
				insertElementAt(constantFirstRow, 0);
			}
		} else modelOffset = 0;

		// Synchronize the dynamic part of the list
		int size = list.size();
		for(int index=0; index<size; index++) {
			E obj = list.get(index);
			if(index>=(getSize()-modelOffset)) addElement(obj);
			else if(!obj.equals(getElementAt(index+modelOffset))) {
				// Objects don't match
				// If this object is found further down the list, then delete up to that object
				int foundIndex = -1;
				for(int searchIndex = index+1; searchIndex<(getSize()-modelOffset); searchIndex++) {
					if(obj.equals(getElementAt(searchIndex+modelOffset))) {
						foundIndex = searchIndex;
						break;
					}
				}
				if(foundIndex!=-1) {
					// No removeRange
					// removeRange(index+modelOffset, foundIndex-1+modelOffset);
					for(
						int removeIndex = foundIndex-1+modelOffset, end = index+modelOffset;
						removeIndex>=end;
						removeIndex--
					) removeElementAt(removeIndex);
				} else {
					// Otherwise, insert in the current index
					insertElementAt(obj, index+modelOffset);
				}
			}
		}
		// Remove any extra
		while((getSize()-modelOffset) > size) removeElementAt(getSize()-1);
	}
1009142
function(value) {
    if (!this.context) return;
    if (this.setter === false) return;
    if (!this.setter) {
      try {
        this.setter = typeof this.expression === 'string'
          ? expressions.parseSetter(this.expression, this.observations.globals, this.observations.formatters)
          : false;
      } catch (e) {
        this.setter = false;
      }
      if (!this.setter) return;
    }

    try {
      var result = this.setter.call(this.context, value);
    } catch(e) {
      return;
    }

    // We can't expect code in fragments outside Observer to be aware of "sync" since observer can be replaced by other
    // types (e.g. one without a `sync()` method, such as one that uses `Object.observe`) in other systems.
    this.sync();
    this.observations.sync();
    return result;
  }
1014810
public synchronized void setSynced(boolean sync) {
        if (synced.get() != sync) {
            // We are changing sync state, so add or remove our master listener as appropriate.
            if (sync && isSendingStatus()) {
                addMasterListener(ourSyncMasterListener);
            } else {
                removeMasterListener(ourSyncMasterListener);
            }

            // Also, if there is a tempo master, and we just got synced, adopt its tempo.
            if (!isTempoMaster() && getTempoMaster() != null) {
                setTempo(getMasterTempo());
            }
        }
        synced.set(sync);
    }
78962
public void trigger(String dataId, InputStream is) {
        List<LoaderListener> listeners = getListeners("");
        //noinspection SynchronizationOnLocalVariableOrMethodParameter
        synchronized (listeners) {
            for (LoaderListener ll : listeners) {
                try {
                    ll.newDataLoaded(dataId, is);
                } catch (Exception e) {
                    LOG.log(Level.SEVERE, "Error calling LoadListener: " + ll, e);
                }
            }
        }
        if (!(dataId==null || dataId.isEmpty())) {
            listeners = getListeners(dataId);
            //noinspection SynchronizationOnLocalVariableOrMethodParameter
            synchronized (listeners) {
                for (LoaderListener ll : listeners) {
                    try {
                        ll.newDataLoaded(dataId, is);
                    } catch (Exception e) {
                        throw new IllegalArgumentException("Failed to load new data: " + ll, e);
                    }
                }
            }
        }
    }
708706
@Override
    public <R, T extends Object> Future<R> callMethodAsync(final String methodName, final T argument) {

        try {
            validateMiddleware();
        } catch (InvalidStateException ex) {
            return FutureProcessor.canceledFuture(ex);
        }

        return GlobalCachedExecutorService.submit(new Callable<R>() {

            private Future<R> internalCallFuture;

            @Override
            public R call() throws Exception {

                final String shortArgument = RPCHelper.argumentToString(argument);

                try {
                    try {
                        logger.debug("Calling method async [" + methodName + "(" + shortArgument + ")] on scope: " + remoteServer.getScope().toString());

                        if (!isConnected()) {
                            try {
                                waitForConnectionState(CONNECTED, CONNECTION_TIMEOUT);
                            } catch (TimeoutException ex) {
                                throw new CouldNotPerformException("Cannot not call async method[" + methodName + "(" + shortArgument + ")] on [" + this + "] in connectionState[" + connectionState + "]", ex);

                            }
                        }
                        final long currentTime = System.nanoTime();
                        remoteServerWatchDog.waitForServiceActivation();
                        internalCallFuture = remoteServer.callAsync(methodName, argument);
                        while (true) {

                            if (TimeUnit.NANOSECONDS.toMillis(System.nanoTime() - currentTime) > RPCHelper.RPC_TIMEOUT) {
                                throw new TimeoutException("RPCMethod call timeout");
                            }

                            try {
                                return internalCallFuture.get(REQUEST_TIMEOUT, TimeUnit.MILLISECONDS);
                            } catch (java.util.concurrent.TimeoutException ex) {


                                // validate connection
                                try {
                                    // if reconnecting do not start a ping but just wait for connecting again
                                    if (getConnectionState() != RECONNECTING) {
                                        ping().get(REQUEST_TIMEOUT, TimeUnit.MILLISECONDS);
                                    } else {
                                        waitForConnectionState(CONNECTING);
                                    }
                                } catch (ExecutionException | java.util.concurrent.TimeoutException | CancellationException exx) {
                                    // cancel call if connection is broken
                                    if (internalCallFuture != null) {
                                        internalCallFuture.cancel(true);
                                    }
                                }
                            } catch (ExecutionException ex) {
                                if (ex.getCause() instanceof RSBException) {
                                    throw new RSBResolvedException("Remote call failed!", (RSBException) ex.getCause());
                                }
                                throw ex;
                            } catch (InterruptedException ex) {
                                Thread.currentThread().interrupt();
                            }

                            // check if thread was interrupted during processing
                            if (Thread.currentThread().isInterrupted()) {
                                throw new InterruptedException();
                            }
                        }


                    } catch (final InterruptedException ex) {
                        if (internalCallFuture != null) {
                            internalCallFuture.cancel(true);
                        }
                        throw ex;
                    } catch (final InvalidStateException ex) {
                        // reinit remote service because middleware connection lost!
                        switch (connectionState) {
                            // only if the connection was established before and no reconnect is ongoing.
                            case CONNECTING:
                            case CONNECTED:
                                try {
                                    reinit();
                                } catch (final CouldNotPerformException exx) {
                                    ExceptionPrinter.printHistory("Recovering middleware connection failed!", exx, logger);
                                }
                        }
                        throw ex;
                    }
                } catch (final CouldNotPerformException | CancellationException | InterruptedException ex) {
                    throw new CouldNotPerformException("Could not call remote Method[" + methodName + "(" + shortArgument + ")] on Scope[" + remoteServer.getScope() + "].", ex);
                }
            }
        });
    }
164434
synchronized void sync()
    {
        try
        {
            // check we have more work to do
            if (allocatePosition.get() <= lastSyncedOffset + SYNC_MARKER_SIZE)
                return;

            // allocate a new sync marker; this is both necessary in itself, but also serves to demarcate
            // the point at which we can safely consider records to have been completely written to
            int nextMarker;
            nextMarker = allocate(SYNC_MARKER_SIZE);
            boolean close = false;
            if (nextMarker < 0)
            {
                // ensure no more of this CLS is writeable, and mark ourselves for closing
                discardUnusedTail();
                close = true;

                // wait for modifications guards both discardedTailFrom, and any outstanding appends
                waitForModifications();

                if (discardedTailFrom < buffer.capacity() - SYNC_MARKER_SIZE)
                {
                    // if there's room in the discard section to write an empty header, use that as the nextMarker
                    nextMarker = discardedTailFrom;
                }
                else
                {
                    // not enough space left in the buffer, so mark the next sync marker as the EOF position
                    nextMarker = buffer.capacity();
                }
            }
            else
            {
                waitForModifications();
            }

            assert nextMarker > lastSyncedOffset;

            // write previous sync marker to point to next sync marker
            // we don't chain the crcs here to ensure this method is idempotent if it fails
            int offset = lastSyncedOffset;
            final PureJavaCrc32 crc = new PureJavaCrc32();
            crc.updateInt((int) (id & 0xFFFFFFFFL));
            crc.updateInt((int) (id >>> 32));
            crc.updateInt(offset);
            buffer.putInt(offset, nextMarker);
            buffer.putInt(offset + 4, crc.getCrc());

            // zero out the next sync marker so replayer can cleanly exit
            if (nextMarker < buffer.capacity())
            {
                buffer.putInt(nextMarker, 0);
                buffer.putInt(nextMarker + 4, 0);
            }

            // actually perform the sync and signal those waiting for it
            buffer.force();

            if (close)
                nextMarker = buffer.capacity();

            lastSyncedOffset = nextMarker;
            syncComplete.signalAll();

            CLibrary.trySkipCache(fd, offset, nextMarker);
            if (close)
                internalClose();
        }
        catch (Exception e) // MappedByteBuffer.force() does not declare IOException but can actually throw it
        {
            throw new FSWriteError(e, getPath());
        }
    }
918940
public void connectAsynch(Object context) {
        if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) {
            Tr.entry(tc, "connectAsynch");
        }

        this.syncObject = null;

        // reset proxy response object
        if (this.proxy != null) {
            this.proxy.setIsProxyResponseValid(false);
        }

        connectCommon((TCPConnectRequestContext) context);

        if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) {
            Tr.exit(tc, "connectAsynch");
        }
    }