Event Dispatcher  v0.1.6-beta.1
Project that offers a small library that allows to subscribe and fire events.
EventPublisher.java
Go to the documentation of this file.
1 package com.fermod.event;
2 
3 import java.util.ArrayList;
4 import java.util.List;
5 import java.util.concurrent.locks.Lock;
6 import java.util.concurrent.locks.ReadWriteLock;
7 import java.util.concurrent.locks.ReentrantReadWriteLock;
8 import java.util.function.Consumer;
9 
15 public abstract class EventPublisher<T> {
16 
17  private final ReadWriteLock readWriteLock = new ReentrantReadWriteLock(true);
18  protected final Lock readLock = readWriteLock.readLock();
19  protected final Lock writeLock = readWriteLock.writeLock();
20 
21  private List<T> listeners = new ArrayList<>();
22 
29  public T registerListener(T listener) {
30 
31  // Lock the list of listeners for writing
32  this.writeLock.lock();
33 
34  try {
35  // Add the listener to the list of registered listeners
36  this.listeners.add(listener);
37  } finally {
38  // Unlock the writer lock
39  this.writeLock.unlock();
40  }
41 
42  return listener;
43  }
44 
50  public void unregisterListener(T listener) {
51 
52  // Lock the list of listeners for writing
53  this.writeLock.lock();
54 
55  try {
56  // Remove the listener from the list of the registered listeners
57  this.listeners.remove(listener);
58  } finally {
59  // Unlock the writer lock
60  this.writeLock.unlock();
61  }
62 
63  }
64 
68  public void unregisterAllListeners() {
69 
70  // Lock the list of listeners for writing
71  this.writeLock.lock();
72 
73  try {
74  // Remove all the listeners from the list of the registered listeners
75  this.listeners.clear();
76  } finally {
77  // Unlock the writer lock
78  this.writeLock.unlock();
79  }
80 
81  }
82 
88  public void notifyListeners(Consumer<? super T> action) {
89 
90  // Lock the list of listeners for reading
91  this.readLock.lock();
92 
93  try {
94  // Execute some function on each of the listeners
95  this.listeners.forEach(action);
96  } finally {
97  // Unlock the reader lock
98  this.readLock.unlock();
99  }
100 
101  }
102 
103 }
void notifyListeners(Consumer<? super T > action)
Notifies and executes on each of the registered listeners the provided function.
void unregisterAllListeners()
Removes all the listeners from the list of the registered listeners.
final ReadWriteLock readWriteLock
T registerListener(T listener)
Adds the specified listener to the list of registered listeners.
void unregisterListener(T listener)
Removes the first occurrence of the specified listener from the list of the registered listeners.
Class that allows to register and notify event listeners.