Quantcast
Channel: Scratch Where It's Itching
Viewing all articles
Browse latest Browse all 73

Hamburger Queue

$
0
0
In my last entry, I presented the Hamburger Pattern and talked about how you can reduce the number of events on a queue by merging them. However, I feel that I should have presented at least one way to merge the events. Here is a simple example of a merging queue. It might not present the best performance, but you will get the basic idea:
public class MergeQueue {private final Map queue = new LinkedHashMap<>();private final BiFunction merger;public MergeQueue(BiFunction merger) {this.merger = merger;
	}public synchronized void push(String key, T value) {
		queue.merge(key, value, merger);
	}public synchronized T getNextMergedValue() {
		Iterator it = queue.values().iterator();
		if (!it.hasNext()) return null;
		T value = it.next();
		it.remove();return value;
	}
}

The whole queue idea is to use the LinkedHashMap properties to both keep data in order of insertion, and keep only one single value for a given key. This queue is given a merger lambda as a parameter in order to tell it how to merge an old and a new value. In the simplest case, you would just replace the old value by the new:

    MergedQueue queue = new MergedQueue<>((oldValue, newValue) -> newValue);


Viewing all articles
Browse latest Browse all 73

Trending Articles