001/* 002 * JGrapes Event Driven Framework 003 * Copyright (C) 2016-2018 Michael N. Lipp 004 * 005 * This program is free software; you can redistribute it and/or modify it 006 * under the terms of the GNU Affero General Public License as published by 007 * the Free Software Foundation; either version 3 of the License, or 008 * (at your option) any later version. 009 * 010 * This program is distributed in the hope that it will be useful, but 011 * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY 012 * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License 013 * for more details. 014 * 015 * You should have received a copy of the GNU Affero General Public License along 016 * with this program; if not, see <http://www.gnu.org/licenses/>. 017 */ 018 019package org.jgrapes.io.util; 020 021import java.beans.ConstructorProperties; 022import java.lang.management.ManagementFactory; 023import java.lang.ref.ReferenceQueue; 024import java.lang.ref.WeakReference; 025import java.nio.Buffer; 026import java.time.Duration; 027import java.util.Collections; 028import java.util.HashMap; 029import java.util.IntSummaryStatistics; 030import java.util.Map; 031import java.util.Optional; 032import java.util.Set; 033import java.util.SortedMap; 034import java.util.TreeMap; 035import java.util.WeakHashMap; 036import java.util.concurrent.ArrayBlockingQueue; 037import java.util.concurrent.BlockingQueue; 038import java.util.concurrent.TimeUnit; 039import java.util.concurrent.atomic.AtomicInteger; 040import java.util.concurrent.atomic.AtomicReference; 041import java.util.function.BiFunction; 042import java.util.function.Supplier; 043import java.util.logging.Level; 044import java.util.logging.Logger; 045import java.util.stream.Collectors; 046import javax.management.InstanceAlreadyExistsException; 047import javax.management.MBeanRegistrationException; 048import javax.management.MBeanServer; 049import javax.management.MalformedObjectNameException; 050import javax.management.NotCompliantMBeanException; 051import javax.management.ObjectName; 052import org.jgrapes.core.Components; 053import org.jgrapes.core.Components.Timer; 054import org.jgrapes.io.IOSubchannel; 055import org.jgrapes.io.events.Output; 056 057/** 058 * A queue based buffer pool. Using buffers from a pool is an important 059 * feature for limiting the computational resources for an {@link IOSubchannel}. 060 * A producer of {@link Output} events that simply creates its own buffers 061 * may produce and enqueue a large number of events that are not consumed 062 * as fast as they are produced. 063 * 064 * Using a buffer pool with a typical size of two synchronizes the 065 * producer and the consumers of events nicely. The producer 066 * (thread) holds one buffer and fills it, the consumer (thread) holds 067 * the other buffer and works with its content. If the producer finishes 068 * before the consumer, it has to stop until the consumer has processed 069 * previous event and releases the buffer. The consumer can continue 070 * without delay, because the data has already been prepared and enqueued 071 * as the next event. 072 * 073 * One of the biggest problems when using a pool can be to identify 074 * leaking buffers, i.e. buffers that are not properly returned to the pool. 075 * This implementation therefore tracks all created buffers 076 * (with a small overhead) and logs a warning if a buffer is no longer 077 * used (referenced) but has not been returned to the pool. If the 078 * log level for {@link ManagedBufferPool} is set to {@link Level#FINE}, 079 * the warning also includes a stack trace of the call to {@link #acquire()} 080 * that handed out the buffer. Providing this information in addition 081 * obviously requires a larger overhead and is therefore limited to the 082 * finer log levels. 083 * 084 * @param <W> the type of the wrapped (managed) buffer 085 * @param <T> the type of the content buffer that is wrapped 086 */ 087@SuppressWarnings({ "PMD.EmptyCatchBlock", "PMD.CouplingBetweenObjects" }) 088public class ManagedBufferPool<W extends ManagedBuffer<T>, T extends Buffer> 089 implements BufferCollector<W> { 090 091 protected final Logger logger 092 = Logger.getLogger(ManagedBufferPool.class.getName()); 093 094 private static long defaultDrainDelay = 1500; 095 private static long acquireWarningLimit = 1000; 096 097 private String name = Components.objectName(this); 098 private BiFunction<T, BufferCollector<W>, W> wrapper; 099 private Supplier<T> bufferFactory; 100 private BufferMonitor bufferMonitor; 101 private BlockingQueue<W> queue; 102 private int bufferSize = -1; 103 private int preservedBufs; 104 private int maximumBufs; 105 private AtomicInteger createdBufs; 106 private long drainDelay = -1; 107 private final AtomicReference<Timer> idleTimer 108 = new AtomicReference<>(null); 109 110 /** 111 * Sets the default delay after which buffers are removed from 112 * the pool. The default value is 1500ms. 113 * 114 * @param delay the delay in ms 115 */ 116 public static void setDefaultDrainDelay(long delay) { 117 defaultDrainDelay = delay; 118 } 119 120 /** 121 * Returns the default drain delay. 122 * 123 * @return the delay 124 */ 125 public static long defaultDrainDelay() { 126 return defaultDrainDelay; 127 } 128 129 /** 130 * Create a pool that contains a varying number of (wrapped) buffers. 131 * The pool is initially empty. When buffers are requested and none 132 * are left in the pool, new buffers are created up to the given 133 * upper limit. Recollected buffers are put in the pool until it holds 134 * the number specified by the lower threshold. Any additional 135 * recollected buffers are discarded. 136 * 137 * @param wrapper the function that converts buffers to managed buffers 138 * @param bufferFactory a function that creates a new buffer 139 * @param lowerThreshold the number of buffers kept in the pool 140 * @param upperLimit the maximum number of buffers 141 */ 142 public ManagedBufferPool(BiFunction<T, BufferCollector<W>, W> wrapper, 143 Supplier<T> bufferFactory, int lowerThreshold, int upperLimit) { 144 this.wrapper = wrapper; 145 this.bufferFactory = bufferFactory; 146 preservedBufs = lowerThreshold; 147 maximumBufs = upperLimit; 148 createdBufs = new AtomicInteger(); 149 queue = new ArrayBlockingQueue<>(lowerThreshold); 150 bufferMonitor = new BufferMonitor(upperLimit); 151 MBeanView.addPool(this); 152 } 153 154 /** 155 * Create a pool that keeps up to the given number of (wrapped) buffers 156 * in the pool and also uses that number as upper limit. 157 * 158 * @param wrapper the function that converts buffers to managed buffers 159 * @param bufferFactory a function that creates a new buffer 160 * @param buffers the number of buffers 161 */ 162 public ManagedBufferPool(BiFunction<T, BufferCollector<W>, W> wrapper, 163 Supplier<T> bufferFactory, int buffers) { 164 this(wrapper, bufferFactory, buffers, buffers); 165 } 166 167 /** 168 * Sets a name for this pool (to be used in status reports). 169 * 170 * @param name the name 171 * @return the object for easy chaining 172 */ 173 public ManagedBufferPool<W, T> setName(String name) { 174 this.name = name; 175 return this; 176 } 177 178 /** 179 * Returns the name of this pool. 180 * 181 * @return the name 182 */ 183 public String name() { 184 return name; 185 } 186 187 /** 188 * Sets the delay after which buffers are removed from 189 * the pool. 190 * 191 * @param delay the delay 192 * @return the object for easy chaining 193 */ 194 public ManagedBufferPool<W, T> setDrainDelay(long delay) { 195 this.drainDelay = delay; 196 return this; 197 } 198 199 private W createBuffer() { 200 createdBufs.incrementAndGet(); 201 W buffer = wrapper.apply(this.bufferFactory.get(), this); 202 bufferMonitor.put(buffer, new BufferProperties()); 203 bufferSize = buffer.capacity(); 204 return buffer; 205 } 206 207 /** 208 * Removes the buffer from the pool. 209 * 210 * @param buffer the buffer to remove 211 */ 212 @SuppressWarnings("PMD.GuardLogStatement") 213 private void removeBuffer(W buffer) { 214 createdBufs.decrementAndGet(); 215 if (bufferMonitor.remove(buffer) == null) { 216 if (logger.isLoggable(Level.FINE)) { 217 logger.log(Level.WARNING, 218 "Attempt to remove unknown buffer from pool.", 219 new Throwable()); 220 } else { 221 logger.warning("Attempt to remove unknown buffer from pool."); 222 } 223 } 224 } 225 226 /** 227 * Returns the size of the buffers managed by this pool. 228 * 229 * @return the buffer size 230 */ 231 public int bufferSize() { 232 if (bufferSize < 0) { 233 createBuffer().unlockBuffer(); 234 } 235 return bufferSize; 236 } 237 238 /** 239 * Acquires a managed buffer from the pool. If the pool is empty, 240 * waits for a buffer to become available. The acquired buffer has 241 * a lock count of one. 242 * 243 * @return the acquired buffer 244 * @throws InterruptedException if the current thread is interrupted 245 */ 246 public W acquire() throws InterruptedException { 247 // Stop draining, because we obviously need this kind of buffers 248 Optional.ofNullable(idleTimer.getAndSet(null)).ifPresent(Timer::cancel); 249 if (createdBufs.get() < maximumBufs) { 250 // Haven't reached maximum, so if no buffer is queued, create one. 251 W buffer = queue.poll(); 252 if (buffer != null) { 253 buffer.lockBuffer(); 254 return buffer; 255 } 256 return createBuffer(); 257 } 258 // Wait for buffer to become available. 259 if (logger.isLoggable(Level.FINE)) { 260 // If configured, log message after waiting some time. 261 W buffer = queue.poll(acquireWarningLimit, TimeUnit.MILLISECONDS); 262 if (buffer != null) { 263 buffer.lockBuffer(); 264 return buffer; 265 } 266 logger.log(Level.FINE, 267 Thread.currentThread().getName() + " waiting > " 268 + acquireWarningLimit + "ms for buffer, while executing:", 269 new Throwable()); 270 } 271 W buffer = queue.take(); 272 buffer.lockBuffer(); 273 return buffer; 274 } 275 276 /** 277 * Re-adds the buffer to the pool. The buffer is cleared. 278 * 279 * @param buffer the buffer 280 * @see org.jgrapes.io.util.BufferCollector#recollect(org.jgrapes.io.util.ManagedBuffer) 281 */ 282 @Override 283 @SuppressWarnings("PMD.AvoidDeeplyNestedIfStmts") 284 public void recollect(W buffer) { 285 if (queue.size() < preservedBufs) { 286 long effectiveDrainDelay 287 = drainDelay > 0 ? drainDelay : defaultDrainDelay; 288 if (effectiveDrainDelay > 0) { 289 // Enqueue 290 buffer.clear(); 291 queue.add(buffer); 292 Timer old = idleTimer.getAndSet(Components.schedule(this::drain, 293 Duration.ofMillis(effectiveDrainDelay))); 294 if (old != null) { 295 old.cancel(); 296 } 297 return; 298 } 299 } 300 // Discard 301 removeBuffer(buffer); 302 } 303 304 @SuppressWarnings({ "PMD.UnusedFormalParameter" }) 305 private void drain(Timer timer) { 306 idleTimer.set(null); 307 while (true) { 308 W buffer = queue.poll(); 309 if (buffer == null) { 310 break; 311 } 312 removeBuffer(buffer); 313 } 314 } 315 316 /* 317 * (non-Javadoc) 318 * 319 * @see java.lang.Object#toString() 320 */ 321 @Override 322 public String toString() { 323 StringBuilder builder = new StringBuilder(50); 324 builder.append("ManagedBufferPool ["); 325 if (queue != null) { 326 builder.append("queue=").append(queue); 327 } 328 builder.append(']'); 329 return builder.toString(); 330 } 331 332 /** 333 * Buffer properties. 334 */ 335 @SuppressWarnings({ "PMD.PublicMemberInNonPublicType", 336 "PMD.AvoidDuplicateLiterals" }) 337 private class BufferProperties { 338 339 private final StackTraceElement[] createdBy; 340 341 /** 342 * Instantiates new buffer properties. 343 */ 344 public BufferProperties() { 345 if (logger.isLoggable(Level.FINE)) { 346 createdBy = Thread.currentThread().getStackTrace(); 347 } else { 348 createdBy = new StackTraceElement[0]; 349 } 350 } 351 352 /** 353 * Returns where the buffer was created. 354 * 355 * @return the stack trace element[] 356 */ 357 @SuppressWarnings("PMD.MethodReturnsInternalArray") 358 public StackTraceElement[] createdBy() { 359 return createdBy; 360 } 361 } 362 363 /** 364 * This is basically a WeakHashMap. We cannot use WeakHashMap 365 * because there is no "hook" into the collection of orphaned 366 * references, which is what we want here. 367 */ 368 @SuppressWarnings({ "PMD.PublicMemberInNonPublicType", 369 "PMD.AvoidSynchronizedStatement" }) 370 private class BufferMonitor { 371 372 private final Entry<W>[] data; 373 private int indexMask; 374 private final ReferenceQueue<W> orphanedEntries 375 = new ReferenceQueue<>(); 376 377 /** 378 * An Entry. 379 * 380 * @param <B> the generic type 381 */ 382 private class Entry<B extends ManagedBuffer<?>> extends WeakReference<B> 383 implements Map.Entry<B, BufferProperties> { 384 /* default */ final int index; 385 /* default */ BufferProperties props; 386 /* default */ Entry<B> next; 387 388 /** 389 * Instantiates a new entry. 390 * 391 * @param buffer the buffer 392 * @param props the props 393 * @param queue the queue 394 * @param index the index 395 * @param next the next 396 */ 397 /* default */ Entry(B buffer, BufferProperties props, 398 ReferenceQueue<B> queue, int index, Entry<B> next) { 399 super(buffer, queue); 400 this.index = index; 401 this.props = props; 402 this.next = next; 403 } 404 405 @Override 406 public B getKey() { 407 return get(); 408 } 409 410 @Override 411 public BufferProperties getValue() { 412 return props; 413 } 414 415 @Override 416 public BufferProperties setValue(BufferProperties props) { 417 this.props = props; 418 return props; 419 } 420 } 421 422 /** 423 * @param data 424 */ 425 @SuppressWarnings({ "unchecked", "PMD.PublicMemberInNonPublicType" }) 426 public BufferMonitor(int maxBuffers) { 427 int lists = 1; 428 while (lists < maxBuffers) { 429 lists <<= 1; 430 indexMask = (indexMask << 1) + 1; 431 } 432 data = new Entry[lists]; 433 } 434 435 /** 436 * Put an entry in the map. 437 * 438 * @param buffer the buffer 439 * @param properties the properties 440 * @return the buffer properties 441 */ 442 @SuppressWarnings({ "PMD.AvoidInstantiatingObjectsInLoops" }) 443 public BufferProperties put(W buffer, BufferProperties properties) { 444 check(); 445 int index = buffer.hashCode() & indexMask; 446 synchronized (data) { 447 Entry<W> entry = data[index]; 448 Entry<W> prev = null; 449 while (true) { 450 if (entry == null) { 451 // Not found, create new. 452 entry = new Entry<>(buffer, properties, 453 orphanedEntries, index, null); 454 if (prev == null) { 455 data[index] = entry; // Is first. 456 } else { 457 prev.next = entry; // Is next (last). 458 } 459 return properties; 460 } 461 if (entry.getKey() == buffer) { // NOPMD 462 // Found, update. 463 BufferProperties old = entry.getValue(); 464 entry.setValue(properties); 465 return old; 466 } 467 prev = entry; 468 entry = entry.next; 469 } 470 } 471 } 472 473 /** 474 * Returns the properties for the given buffer. 475 * 476 * @param buffer the buffer 477 * @return the buffer properties 478 */ 479 @SuppressWarnings({ "unused", "PMD.CompareObjectsWithEquals" }) 480 public BufferProperties get(ManagedBuffer<?> buffer) { 481 check(); 482 int index = buffer.hashCode() & indexMask; 483 synchronized (data) { 484 Entry<W> entry = data[index]; 485 while (entry != null) { 486 if (entry.getKey() == buffer) { 487 return entry.getValue(); 488 } 489 entry = entry.next; 490 } 491 return null; 492 } 493 } 494 495 /** 496 * Removes the given buffer. 497 * 498 * @param buffer the buffer 499 * @return the buffer properties 500 */ 501 @SuppressWarnings("PMD.CompareObjectsWithEquals") 502 public BufferProperties remove(ManagedBuffer<?> buffer) { 503 check(); 504 int index = buffer.hashCode() & indexMask; 505 synchronized (data) { 506 Entry<W> entry = data[index]; 507 Entry<W> prev = null; 508 while (entry != null) { 509 if (entry.getKey() == buffer) { 510 if (prev == null) { 511 data[index] = entry.next; // Was first. 512 } else { 513 prev.next = entry.next; 514 } 515 return entry.getValue(); 516 } 517 prev = entry; 518 entry = entry.next; 519 } 520 return null; 521 } 522 } 523 524 @SuppressWarnings("PMD.CompareObjectsWithEquals") 525 private BufferProperties remove(Entry<W> toBeRemoved) { 526 synchronized (data) { 527 Entry<W> entry = data[toBeRemoved.index]; 528 Entry<W> prev = null; 529 while (entry != null) { 530 if (entry == toBeRemoved) { 531 if (prev == null) { 532 data[toBeRemoved.index] = entry.next; // Was first. 533 } else { 534 prev.next = entry.next; 535 } 536 return entry.getValue(); 537 } 538 prev = entry; 539 entry = entry.next; 540 } 541 return null; 542 } 543 } 544 545 private void check() { 546 while (true) { 547 @SuppressWarnings("unchecked") 548 Entry<W> entry = (Entry<W>) orphanedEntries.poll(); 549 if (entry == null) { 550 return; 551 } 552 // Managed buffer has not been properly recollected, fix. 553 BufferProperties props = remove(entry); 554 if (props == null) { 555 return; 556 } 557 createdBufs.decrementAndGet(); 558 // Create warning 559 if (logger.isLoggable(Level.WARNING)) { 560 @SuppressWarnings("PMD.AvoidInstantiatingObjectsInLoops") 561 final StringBuilder msg = new StringBuilder( 562 "Orphaned buffer from pool "); 563 msg.append(name()); 564 StackTraceElement[] trace = props.createdBy(); 565 if (trace != null) { 566 msg.append(", created"); 567 for (StackTraceElement e : trace) { 568 msg.append(System.lineSeparator()).append("\tat ") 569 .append(e.toString()); 570 } 571 } 572 logger.warning(msg.toString()); 573 } 574 } 575 } 576 } 577 578 /** 579 * An MBean interface for getting information about the managed 580 * buffer pools. Note that created buffer pools are tracked using 581 * weak references. Therefore, the MBean may report more pools than 582 * are really in use. 583 */ 584 public interface ManagedBufferPoolMXBean { 585 586 /** 587 * Information about a single managed pool. 588 */ 589 @SuppressWarnings("PMD.DataClass") 590 class PoolInfo { 591 private final int created; 592 private final int pooled; 593 private final int preserved; 594 private final int maximum; 595 private final int bufferSize; 596 597 /** 598 * Instantiates a new pool info. 599 * 600 * @param created the created 601 * @param pooled the pooled 602 * @param preserved the preserved 603 * @param maximum the maximum 604 * @param bufferSize the buffer size 605 */ 606 @ConstructorProperties({ "created", "pooled", 607 "preserved", "maximum", "bufferSize" }) 608 public PoolInfo(int created, int pooled, 609 int preserved, int maximum, int bufferSize) { 610 this.created = created; 611 this.pooled = pooled; 612 this.preserved = preserved; 613 this.maximum = maximum; 614 this.bufferSize = bufferSize; 615 } 616 617 /** 618 * The number of buffers created by this pool. 619 * 620 * @return the value 621 */ 622 public int getCreated() { 623 return created; 624 } 625 626 /** 627 * The number of buffers pooled (ready to be acquired). 628 * 629 * @return the value 630 */ 631 public int getPooled() { 632 return pooled; 633 } 634 635 /** 636 * The number of buffers preserved. 637 * 638 * @return the value 639 */ 640 public int getPreserved() { 641 return preserved; 642 } 643 644 /** 645 * The maximum number of buffers created by this pool. 646 * 647 * @return the value 648 */ 649 public int getMaximum() { 650 return maximum; 651 } 652 653 /** 654 * The size of the buffers in items. 655 * 656 * @return the buffer size 657 */ 658 public int getBufferSize() { 659 return bufferSize; 660 } 661 } 662 663 /** 664 * Three views on the existing pool. 665 */ 666 class PoolInfos { 667 private final SortedMap<String, PoolInfo> allPools; 668 private final SortedMap<String, PoolInfo> nonEmptyPools; 669 private final SortedMap<String, PoolInfo> usedPools; 670 671 /** 672 * Instantiates a new pool infos. 673 * 674 * @param pools the pools 675 */ 676 public PoolInfos(Set<ManagedBufferPool<?, ?>> pools) { 677 allPools = new TreeMap<>(); 678 nonEmptyPools = new TreeMap<>(); 679 usedPools = new TreeMap<>(); 680 681 @SuppressWarnings("PMD.UseConcurrentHashMap") 682 Map<String, Integer> dupsNext = new HashMap<>(); 683 for (ManagedBufferPool<?, ?> mbp : pools) { 684 String key = mbp.name(); 685 @SuppressWarnings("PMD.AvoidInstantiatingObjectsInLoops") 686 PoolInfo infos = new PoolInfo( 687 mbp.createdBufs.get(), mbp.queue.size(), 688 mbp.preservedBufs, mbp.maximumBufs, 689 mbp.bufferSize()); 690 if (allPools.containsKey(key) 691 || dupsNext.containsKey(key)) { 692 if (allPools.containsKey(key)) { 693 // Found first duplicate, rename 694 allPools.put(key + "#1", allPools.get(key)); 695 allPools.remove(key); 696 dupsNext.put(key, 2); 697 } 698 allPools.put(key + "#" 699 + dupsNext.put(key, dupsNext.get(key) + 1), infos); 700 } else { 701 allPools.put(key, infos); 702 } 703 } 704 for (Map.Entry<String, PoolInfo> e : allPools.entrySet()) { 705 PoolInfo infos = e.getValue(); 706 if (infos.getPooled() > 0) { 707 nonEmptyPools.put(e.getKey(), infos); 708 } 709 if (infos.getCreated() > 0) { 710 usedPools.put(e.getKey(), infos); 711 } 712 } 713 } 714 715 /** 716 * All pools. 717 * 718 * @return the all pools 719 */ 720 public SortedMap<String, PoolInfo> getAllPools() { 721 return allPools; 722 } 723 724 /** 725 * Pools that have at least managed buffer enqueued 726 * (ready to be acquired). 727 * 728 * @return the non empty pools 729 */ 730 public SortedMap<String, PoolInfo> getNonEmptyPools() { 731 return nonEmptyPools; 732 } 733 734 /** 735 * Pools that have at least one associated buffer 736 * (in pool or in use). 737 * 738 * @return the used pools 739 */ 740 public SortedMap<String, PoolInfo> getUsedPools() { 741 return usedPools; 742 } 743 } 744 745 /** 746 * Set the default drain delay. 747 * 748 * @param millis the drain delay in milli seconds 749 */ 750 void setDefaultDrainDelay(long millis); 751 752 /** 753 * Returns the drain delay in milli seconds. 754 * 755 * @return the value 756 */ 757 long getDefaultDrainDelay(); 758 759 /** 760 * Set the acquire warning limit. 761 * 762 * @param millis the limit 763 */ 764 void setAcquireWarningLimit(long millis); 765 766 /** 767 * Returns the acquire warning limit. 768 * 769 * @return the value 770 */ 771 long getAcquireWarningLimit(); 772 773 /** 774 * Informations about the pools. 775 * 776 * @return the map 777 */ 778 PoolInfos getPoolInfos(); 779 780 /** 781 * Summary information about the pooled buffers. 782 * 783 * @return the values 784 */ 785 IntSummaryStatistics getPooledPerPoolStatistics(); 786 787 /** 788 * Summary information about the created buffers. 789 * 790 * @return the values 791 */ 792 IntSummaryStatistics getCreatedPerPoolStatistics(); 793 } 794 795 /** 796 * The MBean view 797 */ 798 @SuppressWarnings("PMD.PublicMemberInNonPublicType") 799 private static final class MBeanView implements ManagedBufferPoolMXBean { 800 801 private static Set<ManagedBufferPool<?, ?>> allPools 802 = Collections.synchronizedSet( 803 Collections.newSetFromMap(new WeakHashMap<>())); 804 805 /** 806 * Adds the pool. 807 * 808 * @param pool the pool 809 */ 810 public static void addPool(ManagedBufferPool<?, ?> pool) { 811 allPools.add(pool); 812 } 813 814 @Override 815 public void setDefaultDrainDelay(long millis) { 816 ManagedBufferPool.setDefaultDrainDelay(millis); 817 } 818 819 @Override 820 public long getDefaultDrainDelay() { 821 return defaultDrainDelay(); 822 } 823 824 @Override 825 public void setAcquireWarningLimit(long millis) { 826 acquireWarningLimit = millis; 827 } 828 829 @Override 830 public long getAcquireWarningLimit() { 831 return acquireWarningLimit; 832 } 833 834 @Override 835 public PoolInfos getPoolInfos() { 836 return new PoolInfos(allPools); 837 } 838 839 @Override 840 public IntSummaryStatistics getPooledPerPoolStatistics() { 841 return allPools.stream().collect( 842 Collectors.summarizingInt(mbp -> mbp.queue.size())); 843 } 844 845 @Override 846 public IntSummaryStatistics getCreatedPerPoolStatistics() { 847 return allPools.stream().collect( 848 Collectors.summarizingInt(mbp -> mbp.createdBufs.get())); 849 } 850 } 851 852 static { 853 try { 854 MBeanServer mbs = ManagementFactory.getPlatformMBeanServer(); 855 ObjectName mxbeanName = new ObjectName("org.jgrapes.io:type=" 856 + ManagedBufferPool.class.getSimpleName() + "s"); 857 mbs.registerMBean(new MBeanView(), mxbeanName); 858 } catch (MalformedObjectNameException | InstanceAlreadyExistsException 859 | MBeanRegistrationException | NotCompliantMBeanException e) { 860 // Does not happen 861 } 862 } 863}