下面列出了java.util.LinkedList#isEmpty ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
static private void setup_extension(DataDstOneofDescriptor child_field, Descriptors.Descriptor container,
Descriptors.OneofDescriptor fd) {
LinkedList<DataVerifyImpl> gen = setup_verifier(container, fd);
if (gen != null && !gen.isEmpty()) {
for (DataVerifyImpl vfy : gen) {
child_field.addVerifier(vfy);
}
} else {
child_field.resetVerifier();
}
if (fd.getOptions().hasExtension(Xresloader.oneofDescription)) {
child_field.mutableExtension().description = fd.getOptions().getExtension(Xresloader.oneofDescription);
}
if (fd.getOptions().hasExtension(Xresloader.oneofSeparator)) {
child_field.mutableExtension().plainSeparator = fd.getOptions().getExtension(Xresloader.oneofSeparator);
}
}
/**
* Searches (by breadth-first search) the node in this model whose user object is equal to the given object.
*
* @param object
* @return The node whose user object is equal to the given object or null
*/
public TreeNode findNodeByUserObject(Object object) {
LinkedList<TreeNode> queue = new LinkedList<TreeNode>();
// initialize the queue by the root node
queue.add(getRootNode());
do {
// dequeue and examine
TreeNode node = queue.poll();
Object currentNodesObject = node.getUserObject();
if (object.equals(currentNodesObject)) {
return node;
} else {
// enqueue successors
for (int i = 0; i < node.getChildCount(); i++) {
queue.add((TreeNode) node.getChildAt(i));
}
}
} while (!queue.isEmpty());
// the node couldn't be found
return null;
}
/**
* @param root
* @return returns a list of all files (including those in sub-directories)
*/
public static List<File> listAllFiles(File root) {
LinkedList<File> files = new LinkedList<>();
if(root.isDirectory()) {
LinkedList<File> toList = new LinkedList<>(Arrays.asList(root.listFiles()));
while(!toList.isEmpty()) {
File f = toList.poll();
if(f.isDirectory()) {
toList.addAll(Arrays.asList(f.listFiles()));
} else {
files.add(f);
}
}
} else {
files.add(root);
}
return files;
}
private static StatsSnapshot computeStatsData(final LinkedList<CallSnapshot> csList) {
StatsSnapshot statsSnapshot = new StatsSnapshot();
synchronized (csList) {
double tps = 0;
double avgpt = 0;
long sum = 0;
if (!csList.isEmpty()) {
CallSnapshot first = csList.getFirst();
CallSnapshot last = csList.getLast();
sum = last.getValue() - first.getValue();
tps = (sum * 1000.0d) / (last.getTimestamp() - first.getTimestamp());
long timesDiff = last.getTimes() - first.getTimes();
if (timesDiff > 0) {
avgpt = (sum * 1.0d) / timesDiff;
}
}
statsSnapshot.setSum(sum);
statsSnapshot.setTps(tps);
statsSnapshot.setAvgpt(avgpt);
}
return statsSnapshot;
}
private void dfsReachRel(int stateFrom, Map<Integer, Integer> stateToId, boolean[][] reachRel,
Map<Integer, Collection<Integer>> wmRelList) {
HashSet<Integer> reached = new HashSet<>();
LinkedList<Integer> toVisit = new LinkedList<>();
toVisit.add(stateFrom);
int id = stateToId.get(stateFrom);
while (!toVisit.isEmpty()) {
int state = toVisit.removeFirst();
// Epsilon Transition
for (Integer to : wmRelList.get(state)) {
if (!reached.contains(to)) {
reachRel[id][stateToId.get(to)] = true;
wmRelList.get(stateFrom).add(to);
toVisit.add(to);
reached.add(to);
}
}
}
}
public TreeNode findKthNode(TreeNode pRoot, int k) {
if (pRoot == null || k <= 0) return null;
LinkedList<TreeNode> stack = new LinkedList<>();
int count = 0;
while (pRoot != null || !stack.isEmpty()) {
while (pRoot != null) {
stack.push(pRoot);
pRoot = pRoot.left;
}
if (!stack.isEmpty()) {
pRoot = stack.pop();
if (++count == k) return pRoot;
pRoot = pRoot.right;
}
}
return null;
}
public void addChild ( final LinkedList<String> path, final ZipEntry zipEntry )
{
final String seg = path.pop ();
Entry child = this.children.get ( seg );
if ( child == null )
{
final List<String> ids = new ArrayList<> ( this.ids );
ids.add ( seg );
child = new Entry ( ids );
this.children.put ( seg, child );
}
if ( path.isEmpty () )
{
child.zipEntry = zipEntry;
}
else
{
child.addChild ( path, zipEntry );
}
}
/**
* protected method to assist in building "pullbackpath" strings for the
* pullback constraint annotations
*
* @param inEdges List of sketchedges
* @param includeLast Include the last or not
* @return path like string
*/
protected String xmlPBJoinPath(final List<SketchEdge> inEdges, final boolean includeLast) {
final LinkedList<SketchEdge> edges = new LinkedList<>(inEdges);
final StringBuilder joinClause = new StringBuilder(quoteId(edges.get(0).getSourceEntity().getName()));
if (!includeLast && !edges.isEmpty()) {
edges.removeLast();
}
for (final SketchEdge e : edges) {
final EntityNode target = e.getTargetEntity();
joinClause.append('(').append(e.getName()).append(")->").append(target.getName());
}
return joinClause.toString();
}
/** Can copy a Treeline to an AreaTree and viceversa.
* Copies the transform, the nodes (with tags and confidence), and the color. The transparency, locked stated and links are not copied. */
static public<A extends Tree<?>, B extends Node<?>> A copyAs(final Tree<?> src, final Class<A> tree_class, final Class<B> node_class) throws Exception {
final String title = "copy of " + src.title + " #" + src.id;
final A t = tree_class.getConstructor(Project.class, String.class).newInstance(src.project, title);
t.at.setTransform(src.at);
t.color = src.color;
t.width = src.width;
t.height = src.height;
final Map<Node<?>,B> rel = new HashMap<Node<?>,B>();
final LinkedList<Node<?>> todo = new LinkedList<Node<?>>();
//t.root = new Treeline.RadiusNode(src.root.x, src.root.y, src.root.la);
todo.add(src.root);
while (!todo.isEmpty()) {
final Node<?> a = todo.removeLast();
// Put all children nodes to the end of the todo list
if (null != a.children)
for (final Node<?> child : a.children)
todo.add(child);
// Copy the content of the 'a' node
final B copy = node_class.getConstructor(Float.TYPE, Float.TYPE, Layer.class).newInstance(a.x, a.y, a.la);
copy.copyProperties(a);
// Store relationship between original and copy
rel.put(a, copy);
// Find parent if any
if (null == a.parent) {
// Set the copy as the root
t.root = (Node)copy; // need to cast
continue;
}
// .. and if found, add the copy to the copied parent:
rel.get(a.parent).add((Node)copy, copy.confidence); // TODO no other way than to cast?
}
// create internals
t.cacheSubtree((Collection)t.root.getSubtreeNodes());
return t;
}
public synchronized V get(C category) {
LinkedList<V> cat = storage.get(category);
if (cat == null || cat.isEmpty())
return constructor == null ? null : constructor.invoke(category);
V found = cat.removeLast();
if (found != null)
resurrect.invoke(found);
return found;
}
public void registerComponent ( final LinkedList<String> prefix, final ComponentFolder componentFolder, final Component component )
{
logger.debug ( "Register - prefix: {}, componentFolder: {}, component: {}", prefix, componentFolder, component );
// first get the name
final String next = prefix.pop ();
if ( prefix.isEmpty () )
{
add ( next, componentFolder, component );
}
else
{
// add another sub level
ComponentNode node = this.nodes.get ( next );
if ( node == null )
{
if ( this.components.containsKey ( next ) )
{
// blocked by component
// remove all folders we might have created
checkRemove ();
// throw exception
throw new IllegalStateException ( "Namespace blocked by other component" );
}
final FolderCommon folder = new FolderCommon ();
this.folder.add ( next, folder, null );
node = new ComponentNode ( this, folder );
this.nodes.put ( next, node );
}
node.registerComponent ( prefix, componentFolder, component );
}
}
@Override
public Subject getRunAsSubject(final BeanContext callingBeanContext) {
final Subject runAsSubject = super.getRunAsSubject(callingBeanContext);
if (runAsSubject != null) {
return runAsSubject;
}
final LinkedList<Subject> stack = RUN_AS_STACK.get();
if (stack.isEmpty()) {
return null;
}
return stack.getFirst();
}
/**
* 计算数据
* @param csList csList
* @return ;
*/
private static StatsSnapshot computeStatsData(final LinkedList<CallSnapshot> csList) {
StatsSnapshot statsSnapshot = new StatsSnapshot();
synchronized (csList) {
double tps = 0;
double avgpt = 0;
long sum = 0;
if (!csList.isEmpty()) {
CallSnapshot first = csList.getFirst();
CallSnapshot last = csList.getLast();
//sum=last-first
sum = last.getValue() - first.getValue();
//tps
tps = (sum * 1000.0d) / (last.getTimestamp() - first.getTimestamp());
long timesDiff = last.getTimes() - first.getTimes();
if (timesDiff > 0) {
//平均rt
avgpt = (sum * 1.0d) / timesDiff;
}
}
statsSnapshot.setSum(sum);
statsSnapshot.setTps(tps);
statsSnapshot.setAvgpt(avgpt);
}
return statsSnapshot;
}
/**
* Takes one selector from end of LRU list of free selectors.
* If there are no selectors awailable, it creates a new selector.
* Also invokes trimIdleSelectors().
*
* @param channel
* @return
* @throws IOException
*/
private synchronized SelectorInfo get(SelectableChannel channel)
throws IOException {
SelectorInfo selInfo = null;
SelectorProvider provider = channel.provider();
// pick the list : rarely there is more than one provider in use.
ProviderInfo pList = providerList;
while (pList != null && pList.provider != provider) {
pList = pList.next;
}
if (pList == null) {
//LOG.info("Creating new ProviderInfo : " + provider.toString());
pList = new ProviderInfo();
pList.provider = provider;
pList.queue = new LinkedList<SelectorInfo>();
pList.next = providerList;
providerList = pList;
}
LinkedList<SelectorInfo> queue = pList.queue;
if (queue.isEmpty()) {
Selector selector = provider.openSelector();
selInfo = new SelectorInfo();
selInfo.selector = selector;
selInfo.queue = queue;
} else {
selInfo = queue.removeLast();
}
trimIdleSelectors(System.currentTimeMillis());
return selInfo;
}
/**
* 题目:滑动窗口的最大值 思路:滑动窗口应当是队列,但为了得到滑动窗口的最大值,队列序可以从两端删除元素,因此使用双端队列。 原则: 对新来的元素k,将其与双端队列中的元素相比较
* 1)前面比k小的,直接移出队列(因为不再可能成为后面滑动窗口的最大值了!),
* 2)前面比k大的X,比较两者下标,判断X是否已不在窗口之内,不在了,直接移出队列,队列的第一个元素是滑动窗口中的最大值
*/
public ArrayList<Integer> maxInWindows(int[] num, int size) {
ArrayList<Integer> ret = new ArrayList<>();
if (num == null) {
return ret;
}
if (num.length < size || size < 1) {
return ret;
}
// 双端队列,用来记录每个窗口的最大值下标
LinkedList<Integer> indexDeque = new LinkedList<>();
for (int i = 0; i < size - 1; i++) {
while (!indexDeque.isEmpty() && num[i] > num[indexDeque.getLast()]) {
indexDeque.removeLast();
}
indexDeque.addLast(i);
}
for (int i = size - 1; i < num.length; i++) {
while (!indexDeque.isEmpty() && num[i] > num[indexDeque.getLast()]) {
indexDeque.removeLast();
}
indexDeque.addLast(i);
if (i - indexDeque.getFirst() + 1 > size) {
indexDeque.removeFirst();
}
ret.add(num[indexDeque.getFirst()]);
}
return ret;
}
@SuppressWarnings({"rawtypes", "unchecked"})
private void scanMethods(LinkedList<MethodInvoker> methods, Map<String, MethodInvoker> toKeyMappers,
Map<String, MethodInvoker> toStringMappers, Set<String> knownProperties)
{
int sizeBefore = methods.size();
for (Iterator<MethodInvoker> iterator = methods.iterator(); iterator.hasNext(); )
{
MethodInvoker methodInvoker = iterator.next();
ConfigPropertyTemplateImpl template;
Class<?> returnType = methodInvoker.getReturnType();
Type genericReturnType = methodInvoker.getGenericReturnType();
String name;
Method method = methodInvoker.getMethod();
if (methodInvoker.isPrivate())
{
if (methodInvoker.isAnnotationPresent(ToKeyMapperFunction.class))
{
this.scanKeyMapper(methodInvoker, toKeyMappers);
iterator.remove();
continue;
}
if (methodInvoker.isAnnotationPresent(ToStringMapperFunction.class))
{
this.scanStringMapper(methodInvoker, toStringMappers);
iterator.remove();
continue;
}
name = this.extractName(methodInvoker);
methodInvoker.ensureAccessible();
if (! knownProperties.add(name))
{
throw new IllegalStateException("Duplicated property: " + name);
}
template = new ConfigPropertyTemplateImpl(this, returnType, genericReturnType, name, cfg -> methodInvoker.invoke(cfg), method);
}
else
{
Pair<ConfigPropertyAction, ActionMatcherResult> resultPair = ActionsRegistry.findMethod(method, knownProperties::contains);
if (resultPair == null)
{
iterator.remove();
continue;
}
ConfigPropertyAction propertyAction = resultPair.getLeft();
if (! propertyAction.getActionName().equals("get") && methodInvoker.isDefault())
{
throw new RuntimeException("Unexpected default implementation of: " + method);
}
ActionMatcherResult matcherResult = resultPair.getRight();
if (! matcherResult.isValidatedName())
{
continue; // wait for validation.
}
name = matcherResult.getPropertyName();
ConfigPropertyTemplateImpl<?> oldTemplate = this.mutableProperties.get(name);
if (oldTemplate != null)
{
template = oldTemplate;
}
else
{
if (! propertyAction.declaresProperty())
{
continue;
}
if (! knownProperties.add(name))
{
throw new IllegalStateException("Duplicated property: " + name);
}
template = new ConfigPropertyTemplateImpl(this, returnType, genericReturnType, name, cfg -> null, method);
}
if (propertyAction.getActionName().equals("get") && methodInvoker.isDefault())
{
this.defaultValueFromDefaultMethod(methodInvoker, template);
}
MethodSignature methodSignature = new MethodSignature(method);
PropertyActionKey propertyActionKey = new PropertyActionKey(propertyAction, methodSignature);
this.mutableActions.put(propertyActionKey, template);
this.actionsDispatcher.put(methodSignature, propertyActionKey);
}
this.order.add(name);
this.mutableProperties.put(name, template);
iterator.remove();
}
if (methods.isEmpty())
{
return;
}
if (sizeBefore == methods.size())
{
throw new IllegalStateException("Can't create config template, can't find how to implement: " + methods);
}
this.scanMethods(methods, toKeyMappers, toStringMappers, knownProperties);
}
private static Set<URL> findReverseSourceRoots(final URL thisSourceRoot, Map<URL, List<URL>> sourceDeps, Map<URL, List<URL>> rootPeers, final FileObject thisFile) {
long startTime = System.currentTimeMillis();
try {
//TODO: from SourceUtils (which filters out source roots that do not belong to open projects):
//Create inverse dependencies
final Map<URL, List<URL>> inverseDeps = new HashMap<URL, List<URL>> ();
for (Map.Entry<URL,List<URL>> entry : sourceDeps.entrySet()) {
final URL u1 = entry.getKey();
final List<URL> l1 = entry.getValue();
for (URL u2 : l1) {
List<URL> l2 = inverseDeps.get(u2);
if (l2 == null) {
l2 = new ArrayList<URL>();
inverseDeps.put (u2,l2);
}
l2.add (u1);
}
}
//Collect dependencies
final Set<URL> result = new HashSet<URL>();
final LinkedList<URL> todo = new LinkedList<URL> ();
todo.add (thisSourceRoot);
List<URL> peers = rootPeers != null ? rootPeers.get(thisSourceRoot) : null;
if (peers != null)
todo.addAll(peers);
while (!todo.isEmpty()) {
final URL u = todo.removeFirst();
if (!result.contains(u)) {
result.add (u);
final List<URL> ideps = inverseDeps.get(u);
if (ideps != null) {
todo.addAll (ideps);
}
}
}
return result;
} finally {
long endTime = System.currentTimeMillis();
Logger.getLogger("TIMER").log(Level.FINE, "Find Reverse Source Roots", //NOI18N
new Object[]{thisFile, endTime - startTime});
}
}
/**
* Returns all the 'configured' network interfaces
*
* @return list of network interfaces / NULL (in case of error)
*/
private static List<Interface> readInterfaces(){
try{
List<Interface> interfacesResult = new ArrayList<Interface>();
Enumeration<NetworkInterface> networkInterfaces = NetworkInterface.getNetworkInterfaces();
LinkedList<NetworkInterface> networkInterfacesList = new LinkedList<NetworkInterface>();
while(networkInterfaces.hasMoreElements()){
networkInterfacesList.addLast(networkInterfaces.nextElement());
}
while(!networkInterfacesList.isEmpty()){
NetworkInterface networkInterface = networkInterfacesList.removeFirst();
// Since there can be subinterfaces, adding all to the networkInterfaces list and processing them.
// Breadth first traversal.
Enumeration<NetworkInterface> networkSubInterfaces = networkInterface.getSubInterfaces();
while(networkSubInterfaces.hasMoreElements()){
networkInterfacesList.addLast(networkSubInterfaces.nextElement());
}
Interface interfaceResult = new Interface();
interfaceResult.name = unNullify(networkInterface.getName());
interfaceResult.macAddress = parseBytesToMacAddress(networkInterface.getHardwareAddress());
List<String> ips = new ArrayList<String>();
Enumeration<InetAddress> inetAddresses = networkInterface.getInetAddresses();
while(inetAddresses.hasMoreElements()){
InetAddress inetAddress = inetAddresses.nextElement();
byte[] ipBytes = inetAddress.getAddress();
if(inetAddress instanceof Inet4Address){
ips.add(parseBytesToIpv4(ipBytes));
}else if(inetAddress instanceof Inet6Address){
ips.add(parseBytesToIpv6(ipBytes));
}else{
logger.log(Level.WARNING, "Unknown address type: " + inetAddress);
}
}
interfaceResult.ips = ips;
interfacesResult.add(interfaceResult);
}
return interfacesResult;
}catch(Exception e){
logger.log(Level.SEVERE, "Failed to poll network interfaces", e);
}
return null;
}
@Override
public void heartbeatCheck(long timeout) {
// 心跳
for (PhysicalNode physicalNode : physicalNodes.values()) {
// 心跳检测, 超时抛弃
// --------------------------------------------------------------------------
long heartbeatTime = TimeUtil.currentTimeMillis() - timeout;
long closeTime = TimeUtil.currentTimeMillis() - (timeout * 2);
LinkedList<BackendConnection> heartBeatCons = getNeedHeartbeatCons(physicalNode.conQueue.getCons(),
heartbeatTime, closeTime);
if (!heartBeatCons.isEmpty()) {
for (BackendConnection conn : heartBeatCons) {
// apiKeyId、 version、 clientId、correlation
int correlationId = Utils.getCorrelationId();
RequestHeader requestHeader = new RequestHeader(ApiKeys.API_VERSIONS.id, (short)1, CLIENT_ID, correlationId);
Struct struct = requestHeader.toStruct();
int size = struct.sizeOf() + 4;
//
ByteBuffer buffer = NetSystem.getInstance().getBufferPool().allocate( size );
buffer.putInt(struct.sizeOf());
struct.writeTo(buffer);
conHeartBeatHanler.doHeartBeat(conn, buffer);
}
}
heartBeatCons.clear();
conHeartBeatHanler.abandTimeoutConns();
// 连接池 动态调整逻辑
// -------------------------------------------------------------------------------
int idleCons = physicalNode.getIdleCount();
int activeCons = physicalNode.getActiveCount();
int minCons = poolCfg.getMinCon();
int maxCons = poolCfg.getMaxCon();
if (LOGGER.isDebugEnabled())
LOGGER.debug("ClusterHeartbeat: host={}, idle={}, active={}, min={}, max={}, lasttime={}",
new Object[] { physicalNode.getHost() + ":" + physicalNode.getPort(), idleCons, activeCons,
minCons, maxCons, System.currentTimeMillis() });
if (idleCons > minCons) {
if (idleCons < activeCons) {
return;
}
// 闲置太多
closeByIdleMany(physicalNode, idleCons - minCons);
} else if (idleCons < minCons) {
if (idleCons > (minCons * 0.5)) {
return;
}
// 闲置太少
if ((idleCons + activeCons) < maxCons) {
int createCount = (int) Math.ceil((minCons - idleCons) / 3F);
createByIdleLitte(physicalNode, idleCons, createCount);
}
}
}
}
private void filterOnDominance(DominatorTreeExceptionFilter filter) {
DominatorEngine engine = filter.getDomEngine();
for (Integer head : new HashSet<>(mapExtPostdominators.keySet())) {
FastFixedSet<Integer> setPostdoms = mapExtPostdominators.get(head);
LinkedList<Statement> stack = new LinkedList<>();
LinkedList<FastFixedSet<Integer>> stackPath = new LinkedList<>();
stack.add(statement.getStats().getWithKey(head));
stackPath.add(factory.spawnEmptySet());
Set<Statement> setVisited = new HashSet<>();
setVisited.add(stack.getFirst());
while (!stack.isEmpty()) {
Statement stat = stack.removeFirst();
FastFixedSet<Integer> path = stackPath.removeFirst();
if (setPostdoms.contains(stat.id)) {
path.add(stat.id);
}
if (path.contains(setPostdoms)) {
continue;
}
if (!engine.isDominator(stat.id, head)) {
setPostdoms.complement(path);
continue;
}
for (StatEdge edge : stat.getSuccessorEdges(StatEdge.TYPE_REGULAR)) {
Statement edge_destination = edge.getDestination();
if (!setVisited.contains(edge_destination)) {
stack.add(edge_destination);
stackPath.add(path.getCopy());
setVisited.add(edge_destination);
}
}
}
if (setPostdoms.isEmpty()) {
mapExtPostdominators.remove(head);
}
}
}