下面列出了java.util.LinkedList#clear ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
private RepositoryChainModuleResolution findBestMatch(List<ComponentMetaDataResolveState> resolveStates, Collection<Throwable> failures) {
LinkedList<ComponentMetaDataResolveState> queue = new LinkedList<ComponentMetaDataResolveState>();
queue.addAll(resolveStates);
LinkedList<ComponentMetaDataResolveState> missing = new LinkedList<ComponentMetaDataResolveState>();
// A first pass to do local resolves only
RepositoryChainModuleResolution best = findBestMatch(queue, failures, missing);
if (best != null) {
return best;
}
// Nothing found - do a second pass
queue.addAll(missing);
missing.clear();
return findBestMatch(queue, failures, missing);
}
public synchronized void remove (String pkey, AuthCacheValue entry) {
LinkedList<AuthCacheValue> list = hashtable.get (pkey);
if (list == null) {
return;
}
if (entry == null) {
list.clear();
return;
}
ListIterator<AuthCacheValue> iter = list.listIterator ();
while (iter.hasNext()) {
AuthenticationInfo inf = (AuthenticationInfo)iter.next();
if (entry.equals(inf)) {
iter.remove ();
}
}
}
@SuppressWarnings("unchecked")
synchronized private final void restructure() {
count = 0;
final LinkedList<SoftReference<A>>[] ls = this.values().toArray(new LinkedList[this.size()]);
for (final LinkedList<SoftReference<A>> l : ls) {
final SoftReference<A>[] s = l.toArray(new SoftReference[l.size()]);
// Remove stale references and crop to maximum SIZE
l.clear();
for (int i=0, c=count; i < s.length && c < SIZE; ++i) {
if (null == s[i].get()) continue; // stale reference
// Re-add good reference
l.add(s[i]);
++c;
}
// Update
count += l.size();
}
}
private RepositoryChainModuleResolution findLatestModule(DependencyMetaData dependency, List<RepositoryResolveState> resolveStates, Collection<Throwable> failures) {
LinkedList<RepositoryResolveState> queue = new LinkedList<RepositoryResolveState>();
queue.addAll(resolveStates);
LinkedList<RepositoryResolveState> missing = new LinkedList<RepositoryResolveState>();
// A first pass to do local resolves only
RepositoryChainModuleResolution best = findLatestModule(dependency, queue, failures, missing);
if (best != null) {
return best;
}
// Nothing found - do a second pass
queue.addAll(missing);
missing.clear();
return findLatestModule(dependency, queue, failures, missing);
}
/**
* @return the image files that have the most recent associated
* transaction IDs. If there are multiple storage directories which
* contain equal images, we'll return them all.
*
* @throws FileNotFoundException if not images are found.
*/
@Override
List<FSImageFile> getLatestImages() throws IOException {
LinkedList<FSImageFile> ret = new LinkedList<FSImageFile>();
for (FSImageFile img : foundImages) {
if (ret.isEmpty()) {
ret.add(img);
} else {
FSImageFile cur = ret.getFirst();
if (cur.txId == img.txId) {
ret.add(img);
} else if (cur.txId < img.txId) {
ret.clear();
ret.add(img);
}
}
}
if (ret.isEmpty()) {
throw new FileNotFoundException("No valid image files found");
}
return ret;
}
private void getParents(LinkedList<WindowContainer> parents) {
parents.clear();
WindowContainer current = this;
do {
parents.addLast(current);
current = current.mParent;
} while (current != null);
}
/**
* Constructor.
* @param hitObject the associated HitObject
* @param line whether a new curve should be generated for each sequential pair
* @param scaled whether to use scaled coordinates
*/
public LinearBezier(HitObject hitObject, boolean line, boolean scaled) {
super(hitObject, scaled);
LinkedList<CurveType> beziers = new LinkedList<CurveType>();
// Beziers: splits points into different Beziers if has the same points (red points)
// a b c - c d - d e f g
// Lines: generate a new curve for each sequential pair
// ab bc cd de ef fg
int controlPoints = hitObject.getSliderX().length + 1;
LinkedList<Vec2f> points = new LinkedList<Vec2f>(); // temporary list of points to separate different Bezier curves
Vec2f lastPoi = null;
for (int i = 0; i < controlPoints; i++) {
Vec2f tpoi = new Vec2f(getX(i), getY(i));
if (line) {
if (lastPoi != null) {
points.add(tpoi);
beziers.add(new Bezier2(points.toArray(new Vec2f[0])));
points.clear();
}
} else if (lastPoi != null && tpoi.equals(lastPoi)) {
if (points.size() >= 2)
beziers.add(new Bezier2(points.toArray(new Vec2f[0])));
points.clear();
}
points.add(tpoi);
lastPoi = tpoi;
}
if (line || points.size() < 2) {
// trying to continue Bezier with less than 2 points
// probably ending on a red point, just ignore it
} else {
beziers.add(new Bezier2(points.toArray(new Vec2f[0])));
points.clear();
}
init(beziers);
}
/**
* Constructor.
* @param hitObject the associated HitObject
* @param line whether a new curve should be generated for each sequential pair
* @param scaled whether to use scaled coordinates
*/
public LinearBezier(HitObject hitObject, boolean line, boolean scaled) {
super(hitObject, scaled);
LinkedList<CurveType> beziers = new LinkedList<CurveType>();
// Beziers: splits points into different Beziers if has the same points (red points)
// a b c - c d - d e f g
// Lines: generate a new curve for each sequential pair
// ab bc cd de ef fg
int controlPoints = hitObject.getSliderX().length + 1;
LinkedList<Vec2f> points = new LinkedList<Vec2f>(); // temporary list of points to separate different Bezier curves
Vec2f lastPoi = null;
for (int i = 0; i < controlPoints; i++) {
Vec2f tpoi = new Vec2f(getX(i), getY(i));
if (line) {
if (lastPoi != null) {
points.add(tpoi);
beziers.add(new Bezier2(points.toArray(new Vec2f[0])));
points.clear();
}
} else if (lastPoi != null && tpoi.equals(lastPoi)) {
if (points.size() >= 2)
beziers.add(new Bezier2(points.toArray(new Vec2f[0])));
points.clear();
}
points.add(tpoi);
lastPoi = tpoi;
}
if (line || points.size() < 2) {
// trying to continue Bezier with less than 2 points
// probably ending on a red point, just ignore it
} else {
beziers.add(new Bezier2(points.toArray(new Vec2f[0])));
points.clear();
}
init(beziers);
}
public static void createOrderedFiles(String [] files, String contents) throws IOException {
LinkedList<FileObject> createdFiles = new LinkedList<>();
for(int i = 0; i < files.length; i++) {
FileObject f = TestUtilities.createFile(files[i], contents);
if(!createdFiles.isEmpty() && createdFiles.getLast().getParent() != f.getParent()) {
FileUtil.setOrder(createdFiles);
createdFiles.clear();
}
createdFiles.add(f);
}
FileUtil.setOrder(createdFiles);
createdFiles.clear();
}
public static void main(String[] args) throws InterruptedException{
WhiteBox wb = WhiteBox.getWhiteBox();
LinkedList<Object> garbageAndRefList = new LinkedList<Object>();
// Creating a 1M large byte array. Since the test specifies the heap
// region size to be 1m this will be a humongous object. We then
// store a pointer to the array in the static object to keep it live
// during the whole test.
humongous_reference_holder = new LargeRef(new byte[1 * 1024 * 1024]);
// Create some garbage and a reference to the humongous object each round.
for (int i = 0; i < 32; i++) {
garbageAndRefList.add(new byte[400*1000]);
garbageAndRefList.add(new LargeRef(humongous_reference_holder.ref()));
// Promote to old, goal is to get rem-set entries for the humongous
// object from different regions. The test specifies MaxTenuringThreshold=0,
// this will make sure we get objects promoted to old at once.
wb.youngGC();
}
// Clear the garbage and reference list.
garbageAndRefList.clear();
// Run a concurrent mark cycle to mark all references but the static one as dead.
wb.g1StartConcMarkCycle();
while (wb.g1InConcurrentMark()) {
Thread.sleep(100);
}
// Run a young collection to make sure humongous object still can't be eagerly reclaimed.
wb.youngGC();
// Will crash/assert if humongous object has been reclaimed.
wb.fullGC();
}
/**
* Tests for attendingToAttendingAllKilledNoAmulet.
*/
@Test
public void testAttendingToAttendingAllKilledNoAmulet() {
LinkedList<String> questHistory = new LinkedList<String>();
for (final String playerSays : ConversationPhrases.GREETING_MESSAGES) {
final Player bob = PlayerTestHelper.createPlayer("bob");
StringBuilder sb=new StringBuilder("started");
for(int i=0;i<creatures.size();i++) {
sb.append(";"+creatures.get(i));
}
bob.setQuest(QUEST_SLOT, sb.toString());
npcEngine.setCurrentState(ConversationStates.IDLE);
npcEngine.step(bob, playerSays);
assertThat(playerSays, npcEngine.getCurrentState(), is(ConversationStates.QUEST_STARTED));
assertEquals(playerSays, "What happened to the amulet? Remember I need it back!", getReply(npc));
questHistory.clear();
questHistory.add("I agreed to help Maerion.");
questHistory.add("I have killed the "+creatures.get(0)+" in the secret room.");
questHistory.add("I have killed the "+creatures.get(1)+" in the secret room.");
questHistory.add("I have killed the "+creatures.get(2)+" in the secret room.");
questHistory.add("I have killed the "+creatures.get(3)+" in the secret room.");
questHistory.add("I have killed the "+creatures.get(4)+" in the secret room.");
questHistory.add("I have killed the "+creatures.get(5)+" in the secret room.");
questHistory.add("I have killed the "+creatures.get(6)+" in the secret room.");
questHistory.add("I have killed the "+creatures.get(7)+" in the secret room.");
questHistory.add("I have killed the "+creatures.get(8)+" in the secret room.");
questHistory.add("I have killed all required creatures.");
questHistory.add("I have no amulet with me.");
assertEquals(questHistory, quest.getHistory(bob));
}
}
private void processArgList(final LinkedList<String> argList) {
while (!argList.isEmpty()) {
final String arg = argList.remove(0);
// skip empty args
if (arg.isEmpty()) {
continue;
}
// user arguments to the script
if ("--".equals(arg)) {
arguments.addAll(argList);
argList.clear();
continue;
}
// If it doesn't start with -, it's a file. But, if it is just "-",
// then it is a file representing standard input.
if (!arg.startsWith("-") || arg.length() == 1) {
files.add(arg);
continue;
}
if (arg.startsWith(definePropPrefix)) {
final String value = arg.substring(definePropPrefix.length());
final int eq = value.indexOf('=');
if (eq != -1) {
// -Dfoo=bar Set System property "foo" with value "bar"
System.setProperty(value.substring(0, eq), value.substring(eq + 1));
} else {
// -Dfoo is fine. Set System property "foo" with "" as it's value
if (!value.isEmpty()) {
System.setProperty(value, "");
} else {
// do not allow empty property name
throw new IllegalOptionException(definePropTemplate);
}
}
continue;
}
// it is an argument, it and assign key, value and template
final ParsedArg parg = new ParsedArg(arg);
// check if the value of this option is passed as next argument
if (parg.template.isValueNextArg()) {
if (argList.isEmpty()) {
throw new IllegalOptionException(parg.template);
}
parg.value = argList.remove(0);
}
// -h [args...]
if (parg.template.isHelp()) {
// check if someone wants help on an explicit arg
if (!argList.isEmpty()) {
try {
final OptionTemplate t = new ParsedArg(argList.get(0)).template;
throw new IllegalOptionException(t);
} catch (final IllegalArgumentException e) {
throw e;
}
}
throw new IllegalArgumentException(); // show help for
// everything
}
if (parg.template.isXHelp()) {
throw new IllegalOptionException(parg.template);
}
set(parg.template.getKey(), createOption(parg.template, parg.value));
// Arg may have a dependency to set other args, e.g.
// scripting->anon.functions
if (parg.template.getDependency() != null) {
argList.addFirst(parg.template.getDependency());
}
}
}
/**
* Get connected components in image.
*
* Take an input {@code image} as an undirected graph where the pixels with value greater than 0 are
* considered to be nodes. The edges between them are created accorging to the specified {@code connectivity} model.
* Then find <a href="http://en.wikipedia.org/wiki/Connected_component_(graph_theory)">connected components</a>
* as defined in graph theory.
*
* @param ip an input image
* @param connectivity one of the connectivity models ({@code CONNECTIVITY_4} or {@code CONNECTIVITY_8})
* @return Vector of ConnectedComponents
* @see ConnectedComponent
*
* @todo This method is much slower than it could be because of too many allocations!
*/
public static Vector<ConnectedComponent> getConnectedComponents(ij.process.ImageProcessor ip, int connectivity) {
assert (ip != null);
assert ((connectivity == CONNECTIVITY_4) || (connectivity == CONNECTIVITY_8));
int[][] map = new int[ip.getWidth()][ip.getHeight()];
for (int x = 0; x < map.length; x++) {
for (int y = 0; y < map[x].length; y++) {
map[x][y] = 0; // member of no component
}
}
Point<Integer> p;
ConnectedComponent c;
Vector<ConnectedComponent> components = new Vector<ConnectedComponent>();
LinkedList<Point<Integer>> queue = new LinkedList<Point<Integer>>();
int counter = 0;
boolean n, s, w, e;
for (int x = 0; x < map.length; x++) {
for (int y = 0; y < map[x].length; y++) {
if (map[x][y] > 0) continue; // already member of another component
if (ip.getPixelValue(x, y) == 0.0f) continue; // disabled pixel
// new component
counter++;
queue.clear();
queue.push(new Point<Integer>(x, y));
c = new ConnectedComponent();
while (!queue.isEmpty()) {
p = queue.pop();
int px = p.getX().intValue();
int py = p.getY().intValue();
if (map[px][py] > 0) continue; // already member of another component
if (ip.getPixelValue(px, py) == 0.0f) continue; // disabled pixel
map[px][py] = counter;
c.points.add(new Point<Float>(p.getX().floatValue(), p.getY().floatValue(), ip.getPixelValue(px, py)));
w = (px > 0); // west
n = (py > 0); // north
e = (px < (map.length - 1)); // east
s = (py < (map[px].length - 1)); // south
if(w) queue.push(new Point<Integer>(px - 1, py)); // west
if(n) queue.push(new Point<Integer>(px, py - 1)); // north
if(e) queue.push(new Point<Integer>(px + 1, py)); // east
if(s) queue.push(new Point<Integer>(px, py + 1)); // south
if(connectivity == CONNECTIVITY_8) {
if(n && w) queue.push(new Point<Integer>(px - 1, py - 1)); // north west
if(n && e) queue.push(new Point<Integer>(px + 1, py - 1)); // north east
if(s && w) queue.push(new Point<Integer>(px - 1, py + 1)); // south west
if(s && e) queue.push(new Point<Integer>(px + 1, py + 1)); // south east
}
}
components.add(c);
}
}
return components;
}
/**
* Tests for quest2.
*/
@Test
public void testAwaitingPhase() {
LinkedList<String> questHistory = new LinkedList<String>();
ThePiedPiper.setPhase(TPP_Phase.TPP_INACTIVE);
ThePiedPiper.switchToNextPhase();
//quest.phaseInactiveToInvasion();
killRats(TPPQuestHelperFunctions.getRatsCount()/2);
questHistory.add("I have killed some rats in Ados city already, and am trying to kill more.");
assertEquals(questHistory, quest.getHistory(player));
// [18:19] Mayor Chalmers shouts: Saddanly, rats captured city, they are living now under all Ados buildings. I am now in need of call Piped Piper, rats exterminator. Thank to all who tryed to clean up Ados, you are welcome to get your reward.
ThePiedPiper.switchToNextPhase();
//quest.phaseInvasionToAwaiting();
en.step(player, "bye"); // in case if previous test was failed
en.step(player, "hi");
assertEquals("On behalf of the citizens of Ados, welcome.", getReply(npc));
en.step(player, "rats");
// assertEquals("I called a rats exterminator. "+
assertEquals("Well, we tried to clean up the city. "+
"You can get a #reward for your help now, ask about #details "+
"if you want to know more.",getReply(npc));
en.step(player, "details");
assertEquals("Well, from the last reward, you killed "+
details()+
"so I will give you " + rewardMoneys + " money as a #reward for that job.", getReply(npc));
assertEquals(questHistory, quest.getHistory(player));
en.step(player, "reward");
assertEquals("Please take " + rewardMoneys + " money, thank you very much for your help.", getReply(npc));
questHistory.clear();
questHistory.add("I have killed some rats in Ados city and got a reward from Mayor Chalmers!");
assertEquals(questHistory, quest.getHistory(player));
en.step(player, "bye");
assertEquals("Good day to you.", getReply(npc));
// [19:20] Mayor Chalmers shouts: Thanx gods, rats is gone now, Pied Piper hypnotized them and lead away to dungeons. Those of you, who helped to Ados city with rats problem, can get your reward now.
ThePiedPiper.getPhaseClass(
ThePiedPiper.getPhase()).phaseToDefaultPhase(new LinkedList<String>());
//quest.phaseAwaitingToInactive();
en.step(player, "hi");
assertEquals("On behalf of the citizens of Ados, welcome.", getReply(npc));
en.step(player, "rats");
assertEquals("Ados isn't being invaded by rats right now. You can still "+
"get a #reward for the last time you helped. You can ask for #details "+
"if you want.", getReply(npc));
en.step(player, "details");
assertEquals("You killed no rats during the #rats invasion. "+
"To get a #reward you have to kill at least "+
"one rat at that time.", getReply(npc));
assertEquals(questHistory, quest.getHistory(player));
en.step(player, "reward");
assertEquals("You didn't kill any rats which invaded the city, so you don't deserve a reward.", getReply(npc));
assertEquals(questHistory, quest.getHistory(player));
en.step(player, "bye");
assertEquals("Good day to you.", getReply(npc));
en.step(player, "hi");
assertEquals("On behalf of the citizens of Ados, welcome.", getReply(npc));
en.step(player, "reward");
assertEquals("You didn't kill any rats which invaded the city, so you don't deserve a reward.", getReply(npc));
assertEquals(questHistory, quest.getHistory(player));
en.step(player, "bye");
assertEquals("Good day to you.", getReply(npc));
}
public static TCPEndpoint getLocalEndpoint(int port,
RMIClientSocketFactory csf,
RMIServerSocketFactory ssf)
{
/*
* Find mapping for an endpoint key to the list of local unique
* endpoints for this client/server socket factory pair (perhaps
* null) for the specific port.
*/
TCPEndpoint ep = null;
synchronized (localEndpoints) {
TCPEndpoint endpointKey = new TCPEndpoint(null, port, csf, ssf);
LinkedList<TCPEndpoint> epList = localEndpoints.get(endpointKey);
String localHost = resampleLocalHost();
if (epList == null) {
/*
* Create new endpoint list.
*/
ep = new TCPEndpoint(localHost, port, csf, ssf);
epList = new LinkedList<TCPEndpoint>();
epList.add(ep);
ep.listenPort = port;
ep.transport = new TCPTransport(epList);
localEndpoints.put(endpointKey, epList);
if (TCPTransport.tcpLog.isLoggable(Log.BRIEF)) {
TCPTransport.tcpLog.log(Log.BRIEF,
"created local endpoint for socket factory " + ssf +
" on port " + port);
}
} else {
synchronized (epList) {
ep = epList.getLast();
String lastHost = ep.host;
int lastPort = ep.port;
TCPTransport lastTransport = ep.transport;
// assert (localHost == null ^ lastHost != null)
if (localHost != null && !localHost.equals(lastHost)) {
/*
* Hostname has been updated; add updated endpoint
* to list.
*/
if (lastPort != 0) {
/*
* Remove outdated endpoints only if the
* port has already been set on those endpoints.
*/
epList.clear();
}
ep = new TCPEndpoint(localHost, lastPort, csf, ssf);
ep.listenPort = port;
ep.transport = lastTransport;
epList.add(ep);
}
}
}
}
return ep;
}
/**
* Set the port of the (shared) default endpoint object.
* When first created, it contains port 0 because the transport
* hasn't tried to listen to get assigned a port, or if listening
* failed, a port hasn't been assigned from the server.
*/
static void setDefaultPort(int port, RMIClientSocketFactory csf,
RMIServerSocketFactory ssf)
{
TCPEndpoint endpointKey = new TCPEndpoint(null, 0, csf, ssf);
synchronized (localEndpoints) {
LinkedList<TCPEndpoint> epList = localEndpoints.get(endpointKey);
synchronized (epList) {
int size = epList.size();
TCPEndpoint lastEp = epList.getLast();
for (TCPEndpoint ep : epList) {
ep.port = port;
}
if (size > 1) {
/*
* Remove all but the last element of the list
* (which contains the most recent hostname).
*/
epList.clear();
epList.add(lastEp);
}
}
/*
* Allow future exports to use the actual bound port
* explicitly (see 6269166).
*/
TCPEndpoint newEndpointKey = new TCPEndpoint(null, port, csf, ssf);
localEndpoints.put(newEndpointKey, epList);
if (TCPTransport.tcpLog.isLoggable(Log.BRIEF)) {
TCPTransport.tcpLog.log(Log.BRIEF,
"default port for server socket factory " + ssf +
" and client socket factory " + csf +
" set to " + port);
}
}
}
public void testPhrasePrefix() throws IOException {
Directory indexStore = newDirectory();
RandomIndexWriter writer = new RandomIndexWriter(random(), indexStore);
add("blueberry pie", writer);
add("blueberry strudel", writer);
add("blueberry pizza", writer);
add("blueberry chewing gum", writer);
add("bluebird pizza", writer);
add("bluebird foobar pizza", writer);
add("piccadilly circus", writer);
IndexReader reader = writer.getReader();
IndexSearcher searcher = newSearcher(reader);
// search for "blueberry pi*":
MultiPhraseQuery.Builder query1builder = new MultiPhraseQuery.Builder();
// search for "strawberry pi*":
MultiPhraseQuery.Builder query2builder = new MultiPhraseQuery.Builder();
query1builder.add(new Term("body", "blueberry"));
query2builder.add(new Term("body", "strawberry"));
LinkedList<Term> termsWithPrefix = new LinkedList<>();
// this TermEnum gives "piccadilly", "pie" and "pizza".
String prefix = "pi";
TermsEnum te = MultiTerms.getTerms(reader,"body").iterator();
te.seekCeil(new BytesRef(prefix));
do {
String s = te.term().utf8ToString();
if (s.startsWith(prefix)) {
termsWithPrefix.add(new Term("body", s));
} else {
break;
}
} while (te.next() != null);
query1builder.add(termsWithPrefix.toArray(new Term[0]));
MultiPhraseQuery query1 = query1builder.build();
assertEquals("body:\"blueberry (piccadilly pie pizza)\"", query1.toString());
query2builder.add(termsWithPrefix.toArray(new Term[0]));
MultiPhraseQuery query2 = query2builder.build();
assertEquals("body:\"strawberry (piccadilly pie pizza)\"", query2.toString());
ScoreDoc[] result;
result = searcher.search(query1, 1000).scoreDocs;
assertEquals(2, result.length);
result = searcher.search(query2, 1000).scoreDocs;
assertEquals(0, result.length);
// search for "blue* pizza":
MultiPhraseQuery.Builder query3builder = new MultiPhraseQuery.Builder();
termsWithPrefix.clear();
prefix = "blue";
te.seekCeil(new BytesRef(prefix));
do {
if (te.term().utf8ToString().startsWith(prefix)) {
termsWithPrefix.add(new Term("body", te.term().utf8ToString()));
}
} while (te.next() != null);
query3builder.add(termsWithPrefix.toArray(new Term[0]));
query3builder.add(new Term("body", "pizza"));
MultiPhraseQuery query3 = query3builder.build();
result = searcher.search(query3, 1000).scoreDocs;
assertEquals(2, result.length); // blueberry pizza, bluebird pizza
assertEquals("body:\"(blueberry bluebird) pizza\"", query3.toString());
// test slop:
query3builder.setSlop(1);
query3 = query3builder.build();
result = searcher.search(query3, 1000).scoreDocs;
// just make sure no exc:
searcher.explain(query3, 0);
assertEquals(3, result.length); // blueberry pizza, bluebird pizza, bluebird
// foobar pizza
MultiPhraseQuery.Builder query4builder = new MultiPhraseQuery.Builder();
expectThrows(IllegalArgumentException.class, () -> {
query4builder.add(new Term("field1", "foo"));
query4builder.add(new Term("field2", "foobar"));
});
writer.close();
reader.close();
indexStore.close();
}
/**
* Clear the runtime event queue
* @param self self reference
*/
@Function(attributes = Attribute.NOT_ENUMERABLE, where = Where.CONSTRUCTOR)
public static void clearRuntimeEvents(final Object self) {
final LinkedList<RuntimeEvent<?>> q = getEventQueue(self);
q.clear();
}
/**
* Converts a {@link java.awt.image.BufferedImage} to a multi-line text message, using {@link #COLOR_MAP}.
*
* @return A {@link java.lang.String[]} containing the message
*/
public static String[] imageToText(BufferedImage image, boolean trim) {
int height = Preconditions.checkNotNull(image, "Image").getHeight();
int width = image.getWidth();
String[][] message = new String[height][width];
LinkedList<Integer> pendingAlpha = new LinkedList<>();
for (int y = 0; y < height; y++) {
boolean fillAlpha = !trim;
boolean left = false;
for (int x = 0; x < width; x++) {
Color color = new Color(image.getRGB(x, y), true);
if (trim) {
if (color.getAlpha() < 1) {
pendingAlpha.add(x);
left = (left || x == 0);
} else {
if (!left) {
applyPendingAlpha(pendingAlpha, message[y]);
} else {
pendingAlpha.clear();
left = false;
}
}
}
ChatColor minecraftColor = rgbToMinecraft(closestColorMatch(color, COLOR_MAP.keySet()));
message[y][x] = minecraftColor == null ? (fillAlpha ? ALPHA_FILLER_CONTENT : "") : minecraftColor.toString() + PIXEL_CHAR;
}
if (!trim) {
applyPendingAlpha(pendingAlpha, message[y]);
}
}
String[] messageFinal = new String[height];
for (int y = 0; y < height; y++) {
messageFinal[y] = StringUtils.join(message[y]);
}
return messageFinal;
}
@Override
public void heartbeatCheck(long timeout) {
// 心跳检测, 超时抛弃
// --------------------------------------------------------------------------
long heartbeatTime = System.currentTimeMillis() - timeout;
long closeTime = System.currentTimeMillis() - timeout * 2;
LinkedList<BackendConnection> heartBeatCons = getNeedHeartbeatCons( physicalNode.conQueue.getCons(), heartbeatTime, closeTime);
for (BackendConnection conn : heartBeatCons) {
conHeartBeatHanler.doHeartBeat(conn, PING );
}
heartBeatCons.clear();
conHeartBeatHanler.abandTimeoutConns();
// 连接池 动态调整逻辑
// -------------------------------------------------------------------------------
int idleCons = this.getIdleCount();
int activeCons = this.getActiveCount();
int minCons = poolCfg.getMinCon();
int maxCons = poolCfg.getMaxCon();
if ( LOGGER.isDebugEnabled() ) {
LOGGER.debug( "Sthandalone heartbeat: 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(this.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(this.physicalNode, idleCons, createCount);
}
}
// if ( ( (idleCons + activeCons) < maxCons ) && idleCons < minCons ) {
// //闲置太少
// int createCount = (int)Math.ceil( (minCons - idleCons) / 3F );
// createByIdleLitte(this.physicalNode, idleCons, createCount);
//
// } else if ( idleCons > minCons ) {
// //闲置太多
// closeByIdleMany(this.physicalNode, idleCons - minCons );
// }
}