fork download
  1. import java.util.Map;
  2. import java.util.concurrent.ConcurrentHashMap;
  3.  
  4. class ListenerMap {
  5.  
  6. final Map<Integer, Integer> listeners = new ConcurrentHashMap<>();
  7.  
  8. void increaseListeners(final int id) {
  9. listeners.merge(id, 1, Integer::sum);
  10. }
  11.  
  12. void decreaseListeners(final int id) {
  13. listeners.computeIfPresent(id, ($, count) -> {
  14. if (count == 1) {
  15. /* no more listeners -- do something ? */
  16. System.out.println("no more listeners for " + id);
  17. }
  18. return count - 1;
  19. });
  20. }
  21. }
  22.  
  23. class Ideone {
  24.  
  25. public static void main(final String[] argv) {
  26. final ListenerMap map = new ListenerMap();
  27.  
  28. map.increaseListeners(1);
  29. map.increaseListeners(2);
  30. map.increaseListeners(2);
  31.  
  32. for (int i = 0; i <= 2; ++i) {
  33. map.decreaseListeners(i);
  34. }
  35. }
  36. }
Success #stdin #stdout 0.08s 1372672KB
stdin
Standard input is empty
stdout
no more listeners for 1