Skip to content

Commit

Permalink
allow the option to use an external pool in MessageDispatcher (#137)
Browse files Browse the repository at this point in the history
* allow the option to use an external pool

* add null check for pool parameter

* change POOL member name to lowercase

---------

Co-authored-by: Tomski <[email protected]>
  • Loading branch information
damcaoson and Tom-Ski authored Oct 1, 2024
1 parent 7287d58 commit 6726e34
Showing 1 changed file with 14 additions and 5 deletions.
19 changes: 14 additions & 5 deletions gdx-ai/src/com/badlogic/gdx/ai/msg/MessageDispatcher.java
Original file line number Diff line number Diff line change
Expand Up @@ -30,13 +30,15 @@ public class MessageDispatcher implements Telegraph {

private static final String LOG_TAG = MessageDispatcher.class.getSimpleName();

private static final Pool<Telegram> POOL = new Pool<Telegram>(16) {
private static final Pool<Telegram> POOL_GLOBAL = new Pool<Telegram>(16) {
@Override
protected Telegram newObject () {
return new Telegram();
}
};

private final Pool<Telegram> pool;

private PriorityQueue<Telegram> queue;

private IntMap<Array<Telegraph>> msgListeners;
Expand All @@ -47,6 +49,13 @@ protected Telegram newObject () {

/** Creates a {@code MessageDispatcher} */
public MessageDispatcher () {
this(POOL_GLOBAL);
}

public MessageDispatcher (Pool<Telegram> pool) {
if (pool == null)
throw new IllegalArgumentException("pool cannot be null");
this.pool = pool;
this.queue = new PriorityQueue<Telegram>();
this.msgListeners = new IntMap<Array<Telegraph>>();
this.msgProviders = new IntMap<Array<TelegramProvider>>();
Expand Down Expand Up @@ -180,7 +189,7 @@ public void clearProviders () {
/** Removes all the telegrams from the queue and releases them to the internal pool. */
public void clearQueue () {
for (int i = 0; i < queue.size(); i++) {
POOL.free(queue.get(i));
pool.free(queue.get(i));
}
queue.clear();
}
Expand Down Expand Up @@ -466,7 +475,7 @@ public void dispatchMessage (float delay, Telegraph sender, Telegraph receiver,
throw new IllegalArgumentException("Sender cannot be null when a return receipt is needed");

// Get a telegram from the pool
Telegram telegram = POOL.obtain();
Telegram telegram = pool.obtain();
telegram.sender = sender;
telegram.receiver = receiver;
telegram.message = msg;
Expand Down Expand Up @@ -499,7 +508,7 @@ public void dispatchMessage (float delay, Telegraph sender, Telegraph receiver,
boolean added = queue.add(telegram);

// Return it to the pool if has been rejected
if (!added) POOL.free(telegram);
if (!added) pool.free(telegram);

if (debugEnabled) {
if (added)
Expand Down Expand Up @@ -598,7 +607,7 @@ private void discharge (Telegram telegram) {
discharge(telegram);
} else {
// Release the telegram to the pool
POOL.free(telegram);
pool.free(telegram);
}
}

Expand Down

0 comments on commit 6726e34

Please sign in to comment.