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 013 * License for more details. 014 * 015 * You should have received a copy of the GNU Affero General Public License 016 * along with this program; if not, see <http://www.gnu.org/licenses/>. 017 */ 018 019package org.jgrapes.core; 020 021import java.lang.ref.ReferenceQueue; 022import java.lang.ref.WeakReference; 023import java.time.Duration; 024import java.time.Instant; 025import java.util.Collections; 026import java.util.Comparator; 027import java.util.HashMap; 028import java.util.HashSet; 029import java.util.Iterator; 030import java.util.Map; 031import java.util.PriorityQueue; 032import java.util.Queue; 033import java.util.Set; 034import java.util.WeakHashMap; 035import java.util.concurrent.ExecutorService; 036import java.util.concurrent.Executors; 037import java.util.concurrent.ThreadFactory; 038import java.util.concurrent.atomic.AtomicLong; 039import java.util.logging.Level; 040import org.jgrapes.core.annotation.ComponentManager; 041import org.jgrapes.core.events.Start; 042import org.jgrapes.core.events.Started; 043import org.jgrapes.core.internal.ComponentVertex; 044import org.jgrapes.core.internal.CoreUtils; 045import org.jgrapes.core.internal.GeneratorRegistry; 046 047/** 048 * This class provides some utility functions. 049 */ 050@SuppressWarnings({ "PMD.TooManyMethods", 051 "PMD.ClassWithOnlyPrivateConstructorsShouldBeFinal", 052 "PMD.CouplingBetweenObjects", "PMD.AvoidSynchronizedStatement" }) 053public class Components { 054 055 private static ExecutorService defaultExecutorService 056 = useVirtualThreads() ? Executors.newVirtualThreadPerTaskExecutor() 057 : Executors.newCachedThreadPool( 058 new ThreadFactory() { 059 @SuppressWarnings({ "PMD.MissingOverride" }) 060 public Thread newThread(Runnable runnable) { 061 Thread thread 062 = Executors.defaultThreadFactory() 063 .newThread(runnable); 064 thread.setDaemon(true); 065 return thread; 066 } 067 }); 068 069 private static ExecutorService timerExecutorService 070 = defaultExecutorService; 071 072 /** 073 * JGrapes uses virtual thread by default. However, as of 074 * 2024, some debuggers still have problems with virtual 075 * threads. Therefore it is possible to switch back to 076 * platform threads by starting the JVM with property 077 * `-Djgrapes.useVirtualThreads=false`. 078 * 079 * @return true, if successful 080 */ 081 public static boolean useVirtualThreads() { 082 return Boolean.parseBoolean( 083 System.getProperty("jgrapes.useVirtualThreads", "true")); 084 } 085 086 private Components() { 087 } 088 089 /** 090 * Return the default executor service for the framework. 091 * 092 * @return the defaultExecutorService 093 */ 094 public static ExecutorService defaultExecutorService() { 095 return defaultExecutorService; 096 } 097 098 /** 099 * Set the default executor service for the framework. The default 100 * value is a cached thread pool (see @link 101 * {@link Executors#newCachedThreadPool()}) with daemon threads. 102 * 103 * @param defaultExecutorService the executor service to set 104 */ 105 @SuppressWarnings("PMD.CompareObjectsWithEquals") 106 public static void setDefaultExecutorService( 107 ExecutorService defaultExecutorService) { 108 // If the timer executor service is set to the default 109 // executor service, adjust it to the new value as well. 110 if (timerExecutorService == Components.defaultExecutorService) { 111 timerExecutorService = defaultExecutorService; 112 } 113 Components.defaultExecutorService = defaultExecutorService; 114 } 115 116 /** 117 * Returns a component's manager. For a component that inherits 118 * from {@link org.jgrapes.core.Component} this method simply returns 119 * the component as it is its own manager. 120 * 121 * For components that implement {@link ComponentType} but don't inherit from 122 * {@link org.jgrapes.core.Component} the method returns the value of 123 * the attribute annotated as manager slot. If this attribute is still 124 * empty, this method makes the component the root 125 * of a new tree and returns its manager. 126 * 127 * @param component the component 128 * @return the component (with its manager attribute set) 129 */ 130 public static Manager manager(ComponentType component) { 131 return ComponentVertex.componentVertex(component, null); 132 } 133 134 /** 135 * Returns a component's manager like {@link #manager(ComponentType)}. 136 * If the manager slot attribute is empty, the component is initialized 137 * with its component channel set to the given parameter. Invoking 138 * this method overrides any channel set in the 139 * {@link ComponentManager} annotation. 140 * 141 * This method is usually invoked by the constructor of a class 142 * that implements {@link ComponentType}. 143 * 144 * @param component the component 145 * @param componentChannel the channel that the component's 146 * handlers listen on by default and that 147 * {@link Manager#fire(Event, Channel...)} sends the event to 148 * @return the component (with its manager attribute set) 149 * @see Component#Component(Channel) 150 */ 151 public static Manager manager( 152 ComponentType component, Channel componentChannel) { 153 return ComponentVertex.componentVertex(component, componentChannel); 154 } 155 156 /** 157 * Fires a {@link Start} event with an associated 158 * {@link Started} completion event on the broadcast channel 159 * of the given application and wait for the completion of the 160 * <code>Start</code> event. 161 * 162 * @param application the application to start 163 * @throws InterruptedException if the execution was interrupted 164 */ 165 public static void start(ComponentType application) 166 throws InterruptedException { 167 manager(application).fire(new Start(), Channel.BROADCAST).get(); 168 } 169 170 /** 171 * Wait until all generators and event queues are exhausted. When this 172 * stage is reached, nothing can happen anymore unless a new event is 173 * sent from an external thread. 174 * 175 * @throws InterruptedException if the current thread was interrupted 176 * while waiting 177 */ 178 public static void awaitExhaustion() throws InterruptedException { 179 GeneratorRegistry.instance().awaitExhaustion(); 180 } 181 182 /** 183 * Wait until all generators and event queues are exhausted or 184 * the maximum wait time has expired. 185 * 186 * @param timeout the wait time in milliseconds 187 * @return {@code true} if exhaustion state was reached 188 * @throws InterruptedException if the execution was interrupted 189 * @see #awaitExhaustion() 190 */ 191 public static boolean awaitExhaustion(long timeout) 192 throws InterruptedException { 193 return GeneratorRegistry.instance().awaitExhaustion(timeout); 194 } 195 196 /** 197 * Utility method that checks if an assertion error has occurred 198 * while executing handlers. If so, the error is thrown and 199 * the assertion error store is reset. 200 * <P> 201 * This method is intended for junit tests. It enables easy propagation 202 * of assertion failures to the main thread. 203 * 204 * @throws AssertionError if an assertion error occurred while 205 * executing the application 206 */ 207 public static void checkAssertions() { 208 CoreUtils.checkAssertions(); 209 } 210 211 /** 212 * Returns the full name of the object's class together with an id (see 213 * {@link #objectId(Object)}). The result can be used as a unique 214 * human readable identifier for arbitrary objects. 215 * 216 * @param object 217 * the object 218 * @return the object's name 219 */ 220 public static String fullObjectName(Object object) { 221 if (object == null) { 222 return "<null>"; 223 } 224 StringBuilder builder = new StringBuilder(); 225 builder.append(object.getClass().getName()) 226 .append('#') 227 .append(objectId(object)); 228 return builder.toString(); 229 } 230 231 /** 232 * Returns the simple name of the object's class together with an id 233 * (see {@link #objectId(Object)}). Can be used to create a human 234 * readable, though not necessarily unique, label for an object. 235 * 236 * @param object 237 * the object 238 * @return the object's name 239 */ 240 public static String simpleObjectName(Object object) { 241 if (object == null) { 242 return "<null>"; 243 } 244 StringBuilder builder = new StringBuilder(); 245 builder.append(simpleClassName(object.getClass())) 246 .append('#') 247 .append(objectId(object)); 248 return builder.toString(); 249 } 250 251 /** 252 * Returns the name of the object's class together with an id (see 253 * {@link #objectId(Object)}). May be used to implement {@code toString()} 254 * with identifiable objects. If the log level is "finer", the full 255 * class name will be used for the returned value, else the simple name. 256 * 257 * @param object 258 * the object 259 * @return the object's name 260 */ 261 public static String objectName(Object object) { 262 if (object == null) { 263 return "<null>"; 264 } 265 StringBuilder builder = new StringBuilder(); 266 builder.append(className(object.getClass())) 267 .append('#') 268 .append(objectId(object)); 269 return builder.toString(); 270 } 271 272 private static Map<Object, String> objectIds // NOPMD 273 = new WeakHashMap<>(); 274 private static Map<Class<?>, AtomicLong> idCounters // NOPMD 275 = new WeakHashMap<>(); 276 277 private static String getId(Class<?> scope, Object object) { 278 if (object == null) { 279 return "?"; 280 } 281 synchronized (objectIds) { 282 return objectIds.computeIfAbsent(object, 283 key -> Long.toString(idCounters 284 .computeIfAbsent(scope, newKey -> new AtomicLong()) 285 .incrementAndGet())); 286 287 } 288 } 289 290 /** 291 * Returns the full name or simple name of the class depending 292 * on the log level. 293 * 294 * @param clazz the class 295 * @return the name 296 */ 297 public static String className(Class<?> clazz) { 298 if (CoreUtils.classNames.isLoggable(Level.FINER)) { 299 return clazz.getName(); 300 } else { 301 return simpleClassName(clazz); 302 } 303 } 304 305 /** 306 * Returns the simple name of a class. Contrary to 307 * {@link Class#getSimpleName()}, this method returns 308 * the last segement of the full name for anonymous 309 * classes (instead of an empty string). 310 * 311 * @param clazz the class 312 * @return the name 313 */ 314 public static String simpleClassName(Class<?> clazz) { 315 if (!clazz.isAnonymousClass()) { 316 return clazz.getSimpleName(); 317 } 318 // Simple name of anonymous class is empty 319 String name = clazz.getName(); 320 int lastDot = name.lastIndexOf('.'); 321 if (lastDot <= 0) { 322 return name; 323 } 324 return name.substring(lastDot + 1); 325 } 326 327 /** 328 * Returns an id of the object that is unique within a specific scope. Ids 329 * are generated and looked up in the scope of the object's class unless the 330 * class implements {@link IdInfoProvider}. 331 * 332 * @param object 333 * the object 334 * @return the object's name 335 */ 336 public static String objectId(Object object) { 337 if (object == null) { 338 return "?"; 339 } 340 if (object instanceof IdInfoProvider) { 341 return getId(((IdInfoProvider) object).idScope(), 342 ((IdInfoProvider) object).idObject()); 343 } else { 344 return getId(object.getClass(), object); 345 } 346 } 347 348 /** 349 * Implemented by classes that want a special class (scope) to be used 350 * for looking up their id or want to map to another object for getting the 351 * id (see {@link Components#objectId(Object)}). 352 */ 353 @SuppressWarnings("PMD.ImplicitFunctionalInterface") 354 public interface IdInfoProvider { 355 356 /** 357 * Returns the scope. 358 * 359 * @return the scope 360 */ 361 Class<?> idScope(); 362 363 /** 364 * Returns the object to be used for generating the id. 365 * 366 * @return the object (defaults to {@code this}) 367 */ 368 default Object idObject() { 369 return this; 370 } 371 } 372 373 /** 374 * Instances are added to the scheduler in order to be invoked 375 * at a given time. 376 */ 377 @FunctionalInterface 378 public interface TimeoutHandler { 379 380 /** 381 * Invoked when the timeout occurs. 382 * 383 * @param timer the timer that has timed out and needs handling 384 */ 385 void timeout(Timer timer); 386 } 387 388 /** 389 * Represents a timer as created by 390 * {@link Components#schedule(TimeoutHandler, Instant)}. 391 */ 392 public static class Timer { 393 private final Scheduler scheduler; 394 private final TimeoutHandler timeoutHandler; 395 private Instant scheduledFor; 396 397 private Timer(Scheduler scheduler, 398 TimeoutHandler timeoutHandler, Instant scheduledFor) { 399 this.scheduler = scheduler; 400 this.timeoutHandler = timeoutHandler; 401 this.scheduledFor = scheduledFor; 402 } 403 404 /** 405 * Reschedules the timer for the given instant. 406 * 407 * @param scheduledFor the instant 408 */ 409 public void reschedule(Instant scheduledFor) { 410 scheduler.reschedule(this, scheduledFor); 411 } 412 413 /** 414 * Reschedules the timer for the given duration after now. 415 * 416 * @param scheduledFor the timeout 417 */ 418 public void reschedule(Duration scheduledFor) { 419 reschedule(Instant.now().plus(scheduledFor)); 420 } 421 422 /** 423 * Returns the timeout handler of this timer. 424 * 425 * @return the handler 426 */ 427 public TimeoutHandler timeoutHandler() { 428 return timeoutHandler; 429 } 430 431 /** 432 * Returns the instant that this handler is scheduled for. 433 * 434 * @return the instant or `null` if the timer has been cancelled. 435 */ 436 public Instant scheduledFor() { 437 return scheduledFor; 438 } 439 440 /** 441 * Cancels this timer. 442 */ 443 public void cancel() { 444 scheduler.cancel(this); 445 } 446 } 447 448 /** 449 * Returns the executor service used for executing timers. 450 * 451 * @return the timer executor service 452 */ 453 public static ExecutorService timerExecutorService() { 454 return timerExecutorService; 455 } 456 457 /** 458 * Sets the executor service used for executing timers. 459 * Defaults to the {@link #defaultExecutorService()}. 460 * 461 * @param timerExecutorService the timerExecutorService to set 462 */ 463 public static void setTimerExecutorService( 464 ExecutorService timerExecutorService) { 465 Components.timerExecutorService = timerExecutorService; 466 } 467 468 /** 469 * A general purpose scheduler. 470 */ 471 @SuppressWarnings("PMD.PublicMemberInNonPublicType") 472 private static class Scheduler extends Thread { 473 474 private final Queue<Timer> timers = new PriorityQueue<>(10, 475 Comparator.comparing(Timer::scheduledFor)); 476 477 /** 478 * Instantiates a new scheduler. 479 */ 480 public Scheduler() { 481 (useVirtualThreads() ? ofVirtual() : ofPlatform()) 482 .name("Components.Scheduler").start(this); 483 } 484 485 /** 486 * Schedule the handler and return the resulting timer. 487 * 488 * @param timeoutHandler the timeout handler 489 * @param scheduledFor the scheduled for 490 * @return the timer 491 */ 492 public Timer schedule( 493 TimeoutHandler timeoutHandler, Instant scheduledFor) { 494 Timer timer = new Timer(this, timeoutHandler, scheduledFor); 495 synchronized (timers) { 496 timers.add(timer); 497 timers.notifyAll(); 498 } 499 return timer; 500 } 501 502 private void reschedule(Timer timer, Instant scheduledFor) { 503 synchronized (timers) { 504 timers.remove(timer); 505 timer.scheduledFor = scheduledFor; 506 timers.add(timer); 507 timers.notifyAll(); 508 } 509 } 510 511 private void cancel(Timer timer) { 512 synchronized (timers) { 513 if (timers.remove(timer)) { 514 timers.notifyAll(); 515 } 516 timer.scheduledFor = null; 517 } 518 } 519 520 @Override 521 @SuppressWarnings("PMD.OverridingThreadRun") 522 public void run() { 523 while (true) { 524 while (true) { 525 final Timer first; 526 synchronized (timers) { 527 first = timers.peek(); 528 if (first == null 529 || first.scheduledFor().isAfter(Instant.now())) { 530 break; 531 } 532 timers.poll(); 533 } 534 timerExecutorService.submit( 535 () -> first.timeoutHandler().timeout(first)); 536 } 537 try { 538 synchronized (timers) { 539 if (timers.isEmpty()) { 540 timers.wait(); 541 } else { 542 timers 543 .wait(Math.max(1, 544 Duration.between(Instant.now(), 545 timers.peek().scheduledFor()) 546 .toMillis())); 547 } 548 } 549 } catch (Exception e) { // NOPMD 550 // Keep running. 551 } 552 } 553 } 554 } 555 556 @SuppressWarnings("PMD.FieldDeclarationsShouldBeAtStartOfClass") 557 private static Scheduler scheduler = new Scheduler(); 558 559 /** 560 * Schedules the given timeout handler for the given instance. 561 * 562 * @param timeoutHandler the handler 563 * @param scheduledFor the instance in time 564 * @return the timer 565 */ 566 public static Timer schedule( 567 TimeoutHandler timeoutHandler, Instant scheduledFor) { 568 return scheduler.schedule(timeoutHandler, scheduledFor); 569 } 570 571 /** 572 * Schedules the given timeout handler for the given 573 * offset from now. 574 * 575 * @param timeoutHandler the handler 576 * @param scheduledFor the time to wait 577 * @return the timer 578 */ 579 public static Timer schedule( 580 TimeoutHandler timeoutHandler, Duration scheduledFor) { 581 return scheduler.schedule( 582 timeoutHandler, Instant.now().plus(scheduledFor)); 583 } 584 585 /** 586 * Puts the given key and value in the given {@link Map} and 587 * returns the map. Looks ugly when nested, but comes in handy 588 * sometimes. 589 * 590 * @param <K> the key type 591 * @param <V> the value type 592 * @param map the map 593 * @param key the key 594 * @param value the value 595 * @return the map 596 */ 597 public static <K, V> Map<K, V> put(Map<K, V> map, K key, V value) { 598 map.put(key, value); 599 return map; 600 } 601 602 /** 603 * Provisional replacement for method available in Java 9. 604 * 605 * @return an empty map 606 */ 607 @Deprecated 608 public static <K, V> Map<K, V> mapOf() { 609 return new HashMap<>(); 610 } 611 612 /** 613 * Provisional replacement for method available in Java 9. 614 * 615 * @return an immutable map filled with the given values 616 */ 617 @Deprecated 618 @SuppressWarnings({ "PMD.ShortVariable", "PMD.AvoidDuplicateLiterals" }) 619 public static <K, V> Map<K, V> mapOf(K k1, V v1) { 620 @SuppressWarnings("PMD.UseConcurrentHashMap") 621 Map<K, V> result = new HashMap<>(); 622 result.put(k1, v1); 623 return Collections.unmodifiableMap(result); 624 } 625 626 /** 627 * Provisional replacement for method available in Java 9. 628 * 629 * @return an immutable map filled with the given values 630 */ 631 @Deprecated 632 @SuppressWarnings("PMD.ShortVariable") 633 public static <K, V> Map<K, V> mapOf(K k1, V v1, K k2, V v2) { 634 @SuppressWarnings("PMD.UseConcurrentHashMap") 635 Map<K, V> result = new HashMap<>(); 636 result.put(k1, v1); 637 result.put(k2, v2); 638 return Collections.unmodifiableMap(result); 639 } 640 641 /** 642 * Provisional replacement for method available in Java 9. 643 * 644 * @return an immutable map filled with the given values 645 */ 646 @Deprecated 647 @SuppressWarnings("PMD.ShortVariable") 648 public static <K, V> Map<K, V> mapOf(K k1, V v1, K k2, V v2, K k3, V v3) { 649 @SuppressWarnings("PMD.UseConcurrentHashMap") 650 Map<K, V> result = new HashMap<>(); 651 result.put(k1, v1); 652 result.put(k2, v2); 653 result.put(k3, v3); 654 return Collections.unmodifiableMap(result); 655 } 656 657 /** 658 * Provisional replacement for method available in Java 9. 659 * 660 * @return an immutable map filled with the given values 661 */ 662 @Deprecated 663 @SuppressWarnings("PMD.ShortVariable") 664 public static <K, V> Map<K, V> mapOf(K k1, V v1, K k2, V v2, K k3, V v3, 665 K k4, V v4) { 666 @SuppressWarnings("PMD.UseConcurrentHashMap") 667 Map<K, V> result = new HashMap<>(); 668 result.put(k1, v1); 669 result.put(k2, v2); 670 result.put(k3, v3); 671 result.put(k4, v4); 672 return Collections.unmodifiableMap(result); 673 } 674 675 /** 676 * Provisional replacement for method available in Java 9. 677 * 678 * @return an immutable map filled with the given values 679 */ 680 @Deprecated 681 @SuppressWarnings({ "PMD.ExcessiveParameterList", "PMD.ShortVariable", 682 "PMD.AvoidDuplicateLiterals" }) 683 public static <K, V> Map<K, V> mapOf(K k1, V v1, K k2, V v2, K k3, V v3, 684 K k4, V v4, K k5, V v5) { 685 @SuppressWarnings("PMD.UseConcurrentHashMap") 686 Map<K, V> result = new HashMap<>(); 687 result.put(k1, v1); 688 result.put(k2, v2); 689 result.put(k3, v3); 690 result.put(k4, v4); 691 result.put(k5, v5); 692 return Collections.unmodifiableMap(result); 693 } 694 695 /** 696 * Provisional replacement for method available in Java 9. 697 * 698 * @return an immutable map filled with the given values 699 */ 700 @Deprecated 701 @SuppressWarnings({ "PMD.ExcessiveParameterList", "PMD.ShortVariable" }) 702 public static <K, V> Map<K, V> mapOf(K k1, V v1, K k2, V v2, K k3, V v3, 703 K k4, V v4, K k5, V v5, K k6, V v6) { 704 @SuppressWarnings("PMD.UseConcurrentHashMap") 705 Map<K, V> result = new HashMap<>(); 706 result.put(k1, v1); 707 result.put(k2, v2); 708 result.put(k3, v3); 709 result.put(k4, v4); 710 result.put(k5, v5); 711 result.put(k6, v6); 712 return Collections.unmodifiableMap(result); 713 } 714 715 /** 716 * Provisional replacement for method available in Java 9. 717 * 718 * @return an immutable map filled with the given values 719 */ 720 @Deprecated 721 @SuppressWarnings({ "PMD.ExcessiveParameterList", "PMD.ShortVariable" }) 722 public static <K, V> Map<K, V> mapOf(K k1, V v1, K k2, V v2, K k3, V v3, 723 K k4, V v4, K k5, V v5, K k6, V v6, K k7, V v7) { 724 @SuppressWarnings("PMD.UseConcurrentHashMap") 725 Map<K, V> result = new HashMap<>(); 726 result.put(k1, v1); 727 result.put(k2, v2); 728 result.put(k3, v3); 729 result.put(k4, v4); 730 result.put(k5, v5); 731 result.put(k6, v6); 732 result.put(k7, v7); 733 return Collections.unmodifiableMap(result); 734 } 735 736 /** 737 * Provisional replacement for method available in Java 9. 738 * 739 * @return an immutable map filled with the given values 740 */ 741 @Deprecated 742 @SuppressWarnings({ "PMD.ExcessiveParameterList", "PMD.ShortVariable" }) 743 public static <K, V> Map<K, V> mapOf(K k1, V v1, K k2, V v2, K k3, V v3, 744 K k4, V v4, K k5, V v5, K k6, V v6, K k7, V v7, K k8, V v8) { 745 @SuppressWarnings("PMD.UseConcurrentHashMap") 746 Map<K, V> result = new HashMap<>(); 747 result.put(k1, v1); 748 result.put(k2, v2); 749 result.put(k3, v3); 750 result.put(k4, v4); 751 result.put(k5, v5); 752 result.put(k6, v6); 753 result.put(k7, v7); 754 result.put(k8, v8); 755 return Collections.unmodifiableMap(result); 756 } 757 758 /** 759 * Provisional replacement for method available in Java 9. 760 * 761 * @return an immutable map filled with the given values 762 */ 763 @Deprecated 764 @SuppressWarnings({ "PMD.ExcessiveParameterList", "PMD.ShortVariable" }) 765 public static <K, V> Map<K, V> mapOf(K k1, V v1, K k2, V v2, K k3, V v3, 766 K k4, V v4, K k5, V v5, K k6, V v6, K k7, V v7, K k8, V v8, 767 K k9, V v9) { 768 @SuppressWarnings("PMD.UseConcurrentHashMap") 769 Map<K, V> result = new HashMap<>(); 770 result.put(k1, v1); 771 result.put(k2, v2); 772 result.put(k3, v3); 773 result.put(k4, v4); 774 result.put(k5, v5); 775 result.put(k6, v6); 776 result.put(k7, v7); 777 result.put(k8, v8); 778 result.put(k9, v9); 779 return Collections.unmodifiableMap(result); 780 } 781 782 /** 783 * Provisional replacement for method available in Java 9. 784 * 785 * @return an immutable map filled with the given values 786 */ 787 @Deprecated 788 @SuppressWarnings({ "PMD.ExcessiveParameterList", "PMD.ShortVariable" }) 789 public static <K, V> Map<K, V> mapOf(K k1, V v1, K k2, V v2, K k3, V v3, 790 K k4, V v4, K k5, V v5, K k6, V v6, K k7, V v7, K k8, V v8, 791 K k9, V v9, K k10, V v10) { 792 @SuppressWarnings("PMD.UseConcurrentHashMap") 793 Map<K, V> result = new HashMap<>(); 794 result.put(k1, v1); 795 result.put(k2, v2); 796 result.put(k3, v3); 797 result.put(k4, v4); 798 result.put(k5, v5); 799 result.put(k6, v6); 800 result.put(k7, v7); 801 result.put(k8, v8); 802 result.put(k9, v9); 803 result.put(k10, v10); 804 return Collections.unmodifiableMap(result); 805 } 806 807 /** 808 * An index of pooled items. Each key is associated with a set 809 * of values. Values can be added or retrieved from the set. 810 * 811 * @param <K> the key type 812 * @param <V> the value type 813 */ 814 public static class PoolingIndex<K, V> { 815 816 @SuppressWarnings("PMD.UseConcurrentHashMap") 817 private final Map<K, Set<ValueReference>> backing = new HashMap<>(); 818 private final ReferenceQueue<V> orphanedEntries 819 = new ReferenceQueue<>(); 820 821 @SuppressWarnings({ "PMD.CommentRequired", 822 "PMD.PublicMemberInNonPublicType" }) 823 private class ValueReference extends WeakReference<V> { 824 825 private final K key; 826 827 public ValueReference(K key, V referent) { 828 super(referent, orphanedEntries); 829 this.key = key; 830 } 831 832 /* 833 * (non-Javadoc) 834 * 835 * @see java.lang.Object#hashCode() 836 */ 837 @Override 838 public int hashCode() { 839 V value = get(); 840 if (value == null) { 841 return 0; 842 } 843 return value.hashCode(); 844 } 845 846 /* 847 * (non-Javadoc) 848 * 849 * @see java.lang.Object#equals(java.lang.Object) 850 */ 851 @Override 852 public boolean equals(Object obj) { 853 if (obj == null) { 854 return false; 855 } 856 if (!obj.getClass().equals(ValueReference.class)) { 857 return false; 858 } 859 V value1 = get(); 860 @SuppressWarnings("unchecked") 861 V value2 = ((ValueReference) obj).get(); 862 if (value1 == null || value2 == null) { 863 return false; 864 } 865 return value1.equals(value2); 866 } 867 } 868 869 @SuppressWarnings({ "PMD.CompareObjectsWithEquals" }) 870 private void cleanOrphaned() { 871 while (true) { 872 @SuppressWarnings("unchecked") 873 ValueReference orphaned 874 = (ValueReference) orphanedEntries.poll(); 875 if (orphaned == null) { 876 return; 877 } 878 synchronized (this) { 879 Set<ValueReference> set = backing.get(orphaned.key); 880 if (set == null) { 881 continue; 882 } 883 Iterator<ValueReference> iter = set.iterator(); 884 while (iter.hasNext()) { 885 ValueReference ref = iter.next(); 886 if (ref == orphaned) { 887 iter.remove(); 888 if (set.isEmpty()) { 889 backing.remove(orphaned.key); 890 } 891 break; 892 } 893 } 894 } 895 } 896 } 897 898 /** 899 * Remove all entries. 900 */ 901 public void clear() { 902 backing.clear(); 903 cleanOrphaned(); 904 } 905 906 /** 907 * Checks if the key is in the index. 908 * 909 * @param key the key 910 * @return true, if successful 911 */ 912 public boolean containsKey(Object key) { 913 return backing.containsKey(key); 914 } 915 916 /** 917 * Checks if the index is empty. 918 * 919 * @return true, if is empty 920 */ 921 public boolean isEmpty() { 922 return backing.isEmpty(); 923 } 924 925 /** 926 * Returns all keys. 927 * 928 * @return the sets the 929 */ 930 public Set<K> keySet() { 931 synchronized (this) { 932 return backing.keySet(); 933 } 934 } 935 936 /** 937 * Adds the value to the pool of values associated with the key. 938 * 939 * @param key the key 940 * @param value the value 941 * @return the v 942 */ 943 public V add(K key, V value) { 944 synchronized (this) { 945 cleanOrphaned(); 946 backing.computeIfAbsent(key, k -> new HashSet<>()) 947 .add(new ValueReference(key, value)); 948 return value; 949 } 950 } 951 952 /** 953 * Retrives and removes an item from the pool associated with the key. 954 * 955 * @param key the key 956 * @return the removed item or `null` if the pool is empty 957 */ 958 @SuppressWarnings("PMD.AvoidBranchingStatementAsLastInLoop") 959 public V poll(K key) { 960 synchronized (this) { 961 cleanOrphaned(); 962 Set<ValueReference> set = backing.get(key); 963 if (set == null) { 964 return null; 965 } 966 Iterator<ValueReference> iter = set.iterator(); 967 while (iter.hasNext()) { 968 ValueReference ref = iter.next(); 969 V value = ref.get(); 970 iter.remove(); 971 if (value == null) { 972 continue; 973 } 974 if (set.isEmpty()) { 975 backing.remove(key); 976 } 977 return value; 978 } 979 } 980 return null; 981 } 982 983 /** 984 * Removes all values associated with the key. 985 * 986 * @param key the key 987 */ 988 public void removeAll(K key) { 989 synchronized (this) { 990 cleanOrphaned(); 991 backing.remove(key); 992 } 993 } 994 995 /** 996 * Removes the given value from the pool associated with the given key. 997 * 998 * @param key the key 999 * @param value the value 1000 * @return the v 1001 */ 1002 public V remove(K key, V value) { 1003 synchronized (this) { 1004 cleanOrphaned(); 1005 Set<ValueReference> set = backing.get(key); 1006 if (set == null) { 1007 return null; 1008 } 1009 Iterator<ValueReference> iter = set.iterator(); 1010 while (iter.hasNext()) { 1011 ValueReference ref = iter.next(); 1012 V stored = ref.get(); 1013 boolean found = false; 1014 if (stored == null) { 1015 iter.remove(); 1016 } 1017 if (stored.equals(value)) { 1018 iter.remove(); 1019 found = true; 1020 } 1021 if (set.isEmpty()) { 1022 backing.remove(key); 1023 } 1024 if (found) { 1025 return value; 1026 } 1027 } 1028 } 1029 return null; 1030 } 1031 1032 /** 1033 * Removes the value from the first pool in which it is found. 1034 * 1035 * @param value the value 1036 * @return the value or `null` if the value is not found 1037 */ 1038 public V remove(V value) { 1039 synchronized (this) { 1040 for (Set<ValueReference> set : backing.values()) { 1041 Iterator<ValueReference> iter = set.iterator(); 1042 while (iter.hasNext()) { 1043 ValueReference ref = iter.next(); 1044 V stored = ref.get(); 1045 if (stored == null) { 1046 iter.remove(); 1047 } 1048 if (stored.equals(value)) { 1049 iter.remove(); 1050 return value; 1051 } 1052 } 1053 } 1054 } 1055 return null; 1056 } 1057 1058 /** 1059 * Returns the number of keys in the index. 1060 * 1061 * @return the numer of keys 1062 */ 1063 public int keysSize() { 1064 return backing.size(); 1065 } 1066 1067 } 1068}