How to measure the rate of events through a system - math

I need to measure that rate at which a software system is consuming messages from a message queue and report on that periodically.
Specifically, messages arrive from a message queueing system and I need to report (each second) on the number of messages received within a number of rolling windows - e.g. the last second, the last 5 seconds, the last 30 seconds, etc.
Whilst I'm sure I could build this, I'm not certain that I'd go about it in the most efficient manner! I'm also sure that there are libraries for doing this (I'm using the JVM, so Apache Commons Math springs to mind), but I don't even know the right words to Google for! :-)

Here is my solution based on exponential smoothing. It doesn't require any background threads. You would create 1 instance for each rolling window that you want to track. For each relevant event you would call newEvent on each instance.
public class WindowedEventRate {
private double normalizedRate; // event rate / window
private long windowSizeTicks;
private long lastEventTicks;
public WindowedEventRate(int aWindowSizeSeconds) {
windowSizeTicks = aWindowSizeSeconds * 1000L;
lastEventTicks = System.currentTimeMillis();
}
public double newEvent() {
long currentTicks = System.currentTimeMillis();
long period = currentTicks - lastEventTicks;
lastEventTicks = currentTicks;
double normalizedFrequency = (double) windowSizeTicks / (double) period;
double alpha = Math.min(1.0 / normalizedFrequency, 1.0);
normalizedRate = (alpha * normalizedFrequency) + ((1.0 - alpha) * normalizedRate);
return getRate();
}
public double getRate() {
return normalizedRate * 1000L / windowSizeTicks;
}
}

This is what I ended up writing.
package com.example;
import java.util.Arrays;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
public class BucketCounter {
private final Lock rollLock = new ReentrantLock();
private final int[] bucketSizes;
private final int[] buckets;
private final int[] intervals;
private final AtomicInteger incoming = new AtomicInteger(0);
public BucketCounter(int... bucketSizes) {
if (bucketSizes.length < 1) {
throw new IllegalArgumentException("Must specify at least one bucket size");
}
this.bucketSizes = bucketSizes;
this.buckets = new int[bucketSizes.length];
Arrays.sort(bucketSizes);
if (bucketSizes[0] < 1) {
throw new IllegalArgumentException("Cannot have a bucket of size < 1");
}
intervals = new int[bucketSizes[bucketSizes.length - 1]];
}
public int count(int n) {
return incoming.addAndGet(n);
}
public int[] roll() {
final int toAdd = incoming.getAndSet(0);
rollLock.lock();
try {
final int[] results = new int[buckets.length];
for (int i = 0, n = buckets.length; i < n; i++) {
results[i] = buckets[i] = buckets[i] - intervals[bucketSizes[i] - 1] + toAdd;
}
System.arraycopy(intervals, 0, intervals, 1, intervals.length - 1);
intervals[0] = toAdd;
return results;
} finally {
rollLock.unlock();
}
}
}
Initialise it by passing the different time increments (e.g. 1, 5, 30). Then arrange for a background thread to call roll() every "time period". If you call it every second, then your buckets are 1, 5 and 30 seconds. If you call it every 5 seconds, then your buckets are 5, 25 and 150 seconds, etc. Basically, the buckets are expressed in "number of times roll() is called").
roll() also returns you an array of the current counts for each bucket. Note that these numbers are the raw counts, and are not averaged per time interval. You'll need to do that division yourself if you want to measure "rates" rather than "counts".
Finally, every time an event happens, call count(). I've set up a system with a few of these and I call count(1) on each message to count incoming messages, count(message.size()) on each message to count incoming byte rates, etc.
Hope that helps.

You could probably implement it as an interceptor, so search for interceptor combined with the message queue product name and the language name.

Related

How to represent clock

Is there a built in way to represent clock in dart or flutter? I only want to represent time in 24 hours clock.
P.S. I am currently rolling my own solution because I needed a static, locale insensitive clock which is pretty easy. But I was just looking if there is a way.
P.P.S I owned the backend. So I was able to tweak it to return date.
Old question: I am getting a time back from an API which I want to parse in my flutter app. I had a look at DateTime class but there is no apparent method to parse time as I am not interested in the date. Is there a way to represent only time and parse it in dart? Ex- 20:05:00 which should mean 5 minutes past 8 o'clock.
P.S This is my implementation
extension NumberUtil on int {
bool isBetween(int lowerBound, int upperBound) {
/// Checks if an int is between lower and upper bound both inclusive
return this >= lowerBound && this <= upperBound;
}
}
class Time {
final int hours, minutes, seconds;
Time(this.hours, this.minutes, this.seconds) {
assert( hours.isBetween(0, 24) && minutes.isBetween(0, 60) && seconds.isBetween(0, 60) );
}
factory Time.parse(String string) {
/// String should be in 24 hour format: hh:mm:ss. The caller is responsible
/// for catching the parsing exception because:
/// 1. It should almost never occur.
/// 2. Because this is a UI app, the UI is most suited to handle that by
/// displaying a "something went wrong" dialog
final temp = string.split(':');
assert (temp.length == 3);
return Time(
int.parse(temp[0]),
int.parse(temp[1]),
int.parse(temp[2]),
);
}
int compareTo(Time t) {
/// Performs a 3 way comparison between the this and t. Returns 0 if the two
/// objects are same. Returns 1 if this is greater than t. Returns -1 otherwise
if (this.hours > t.hours) return 1;
if (this.hours < t.hours) return -1;
/// at this point hours is same
if (this.minutes > t.minutes) return 1;
if (this.minutes < t.minutes) return -1;
/// At this point minutes are same
if (this.seconds > t.seconds) return 1;
if (this.seconds < t.seconds) return -1;
/// At this point everything is same
return 0;
}
}
Do you mean this?
currentTime = DateTime.now();
targetTime = DateTime.parse('here some times format');
currentTime.difference(targetTime) or currentTime.difference(targetTime).inHours // this??
or
Do you find this package
https://pub.dev/packages/timeago

Algorithm used to calculate hashcode for segments in ConcurrentHashMap in Java

What is the Algorithm used to calculate hashcode for segments in Concurrent HashMap in Java ?
Firstly we know that Concurrent HashMap is divided into a finite number of segments.
Segment is a final class inside Concurrent HashMap .
The definition of Segment is as below:
/** Inner Segment class plays a significant role **/
protected static final class Segment {
protected int count;
protected synchronized int getCount() {
return this.count;
}
protected synchronized void synch() {}
}
/** Segment Array declaration **/
public final Segment[] segments = new Segment[32];//By default
// i am taking as 32.
Let me explain by taking put method of ConcurrentHashMap class.
put(Object key, Object value)
Before placing this map into anyone one of those 32 segments we need to
calculate the hashcode right.
First we calculate the hash of key:
int hashVal = hash(key);
static int hash(Object x) {
int h = x.hashCode();
return (h << 7) - h + (h >>> 9) + (h >>> 17);
}
After getting the hashVal we can decide the Segment as below:
Segment seg = segments[(hash & 0x1F)];
// segments is an array defined above
This is just for understanding refer oracle docs for their practices.

Retouching several images in several Task

Generalities : explanations about my program and its functioning
I am working on a photo-retouching JavaFX application. The final user can load several images. When he clicks on the button REVERSE, a Task is launched for each image using an Executor. Each of these Task executes the reversal algorithm : it fills an ArrayBlockingQueue<Pixel> (using add method).
When the final user clicks on the button REVERSE, as I said, these Task are launched. But just after these statements, I tell the JavaFX Application Thread to draw the Pixel of the ArrayBlockingQueue<Pixel> (using remove method).
Thus, there are parallelism and concurrency (solved by the ArrayBlockingQueue<Pixel>) between the JavaFX Application Thread and the Task, and between the Task themselves.
To draw the Pixel of the ArrayBlockingQueue<Pixel>, the JavaFX Application Thread starts an AnimationTimer. The latter contains the previously-mentionned remove method. This AnimationTimer is started for each image.
I think you're wondering yourself how this AnimationTimer can know to what image belongs the Pixel it has removed ? In fact, each Pixel has an attribute writable_image that specifies the image to what it belongs.
My problems
Tell me if I'm wrong, but my program should work. Indeed :
My JavaFX Application Thread is the only thread that change the GUI (and it's required in JavaFX) : the Task just do the calculations.
There is not concurrency, thanks to the BlockingQueue I use (in particular, there isn't possibility of draining).
The AnimationTimer knows to what image belongs each Pixel.
However, it's (obviously !) not the case (otherwise I wouldn't have created this question haha !).
My problem is that my JavaFX Application freezes (first problem), after having drawn only some reversed pixels (not all the pixels). On the last loaded image moreover (third problem).
A detail that could be the problems' cause
But I would need your opinion.
The AnimationTimer of course doesn't draw the reversed pixels of each image directly : this is animated. The final user can see each pixel of an image being reversed, little by little. It's very practical in other algorithms as the creation of a circle, because the user can "look" how the algorithm works.
But to do that, the AnimationTimer needs to read a variable called max. This variable is modified (writen) in... each Task. But it's an AtomicLong. So IF I AM NOT WRONG, there isn't any problem of concurrency between the Task themselves, or between the JavaFX Application Thread and these Task.
However, it could be the problem : indeed, the max's value could be 2000 in Task n°1 (= in image n°1), and 59 in Task n°2 (= in image n°2). The problem is the AnimationTimer must use 2000 for the image n°1, and 59 for the n°2. But if the Task n°1 et n°2 have finished, the only value known by the AnimationTimer would be 59...
Sources
When the user clicks on the button REVERSE
We launch the several Task and start several times the AnimationTimer. CLASS : RightPane.java
WritableImage current_writable_image;
for(int i = 0; i < this.gui.getArrayListImageViewsImpacted().size(); i++) {
current_writable_image = (WritableImage) this.gui.getArrayListImageViewsImpacted().get(i).getImage();
this.gui.getGraphicEngine().executor.execute(this.gui.getGraphicEngine().createTask(current_writable_image));
}
for(int i = 0; i < this.gui.getArrayListImageViewsImpacted().size(); i++) {
current_writable_image = (WritableImage) this.gui.getArrayListImageViewsImpacted().get(i).getImage();
this.gui.getImageAnimation().setWritableImage(current_writable_image);
this.gui.getImageAnimation().startAnimation();
}
The Task are part of the CLASS GraphicEngine, which contains an Executor :
public final Executor executor = Executors.newCachedThreadPool(runnable -> {
Thread t = new Thread(runnable);
t.setDaemon(true);
return t ;
});
public Task createTask(WritableImage writable_image) {
int image_width = (int) writable_image.getWidth(), image_height = (int) writable_image.getHeight();
Task ret = new Task() {
protected Void call() {
switch(operation_to_do) {
case "reverse" :
gui.getImageAnimation().setMax(image_width*image_height); // USE OF "MAX" VARIABLE
reverseImg(writable_image);
break;
}
return null;
}
};
return ret;
}
The same CLASS, GraphicEngine, also contains the reversal algorithm :
private void reverseImg(WritableImage writable_image) {
int image_width = (int) writable_image.getWidth(), image_height = (int) writable_image.getHeight();
BlockingQueue<Pixel> updates = gui.getUpdates();
PixelReader pixel_reader = writable_image.getPixelReader();
double[] rgb_reversed;
for (int x = 0; x < image_width; x++) {
for (int y = 0; y < image_height; y++) {
rgb_reversed = PhotoRetouchingFormulas.reverse(pixel_reader.getColor(x, y).getRed(), pixel_reader.getColor(x, y).getGreen(), pixel_reader.getColor(x, y).getBlue());
updates.add(new Pixel(x, y, Color.color(rgb_reversed[0], rgb_reversed[1], rgb_reversed[2], pixel_reader.getColor(x, y).getOpacity()), writable_image));
}
}
}
Finally, here is the code of the CLASS AnimationTimer. There is nothing particular. Note the variable max is used here too (and in the CLASS GraphicEngine : setMax).
public class ImageAnimation extends AnimationTimer {
private Gui gui;
private AtomicLong max, speed, max_delay;
private long count, start;
private WritableImage writable_image;
ImageAnimation (Gui gui) {
this.gui = gui;
this.count = 0;
this.start = -1;
this.max = new AtomicLong(Long.MAX_VALUE);
this.max_delay = new AtomicLong(999_000_000);
this.speed = new AtomicLong(this.max_delay.get());
}
public void setMax(long max) {
this.max.set(max);
}
public void setSpeed(long speed) { this.speed.set(speed); }
public double getMaxDelay() { return this.max_delay.get(); }
#Override
public void handle(long timestamp) {
if (start < 0) {
start = timestamp ;
return ;
}
ArrayList<Pixel> list_sorted_pixels = new ArrayList<>();
BlockingQueue<Pixel> updates = this.gui.getUpdates();
for(Pixel new_pixel : updates) {
if(new_pixel.getWritableImage() == writable_image) {
list_sorted_pixels.add(new_pixel);
}
}
while (list_sorted_pixels.size() > 0 && timestamp - start > (count * this.speed.get()) / (writable_image.getWidth()) && !updates.isEmpty()) {
Pixel update = list_sorted_pixels.remove(0);
updates.remove(update);
count++;
if (update.getX() >= 0 && update.getY() >= 0) {
writable_image.getPixelWriter().setColor(update.getX(), update.getY(), update.getColor());
}
}
if (count >= max.get()) {
this.count = 0;
this.start = -1;
this.max.set(Long.MAX_VALUE);
stop();
}
}
public void setWritableImage(WritableImage writable_image) { this.writable_image = writable_image; }
public void startAnimation() {
this.start();
}
}

Depth first search orders

In depth first search, whenever a node is visited, we have to again take one of its adjacent nodes and the perform this process for this adjacent node. Depending on this , there may be multiple Depth first search orders. So , is there any way to count the total different DFS orders in a graph without applying the algorithm and manually calculating? Please give me the solution as soon as possible..
you can do it by counting the nodes at each level and keep multiplying every time going to the next level.
LinkedList<Node> connections = startNode.connections;
long totalOrders = 1L;
while(!connections.isEmpty()){
LinkedList<Node> newConnections = new LinkedList<>();
List<Integer> conSizes = new LinkedList()<>;
for (Node connection : connections) {
if(!connection.visited){
connection.visited = true;
newConnections.addAll(connection.connections);
totalOrders = totalOrders * factorial(connection.connections.size());
}
}
totalOrders = totalOrders * factorial(connections.size());
connections = newConnections;
}
System.out.println(totalOrders)
public static long factorial(int n) {
long fact = 1; // this will be the result
for (int i = 1; i <= n; i++) {
fact *= i;
}
return fact;
}

Coin Change Dynamic Programming

QUESTION:
I'm having trouble finding the minimum amount of coins needed to reach a specific sum. I'm pretty sure this is done easiest recursively and using the dynamic programming methodology, I should basically get Math.min("takeACoin","leaveACoin");
Unfortunately, My code doesn't terminate though I do have if statements that terminate under the condition that the sum is met, the array of coins is depleted, or if the sum is over. Please look at my code below and let me know what I'm doing wrong and especially why my code continues executing until it receives a stackoverflow error though I have the appropriate terminating conditions.
CODE:
private static final int S = 3;
public static int arr[] = {1,2};
public static void main(String[] args) {
Interview i = new Interview();
i.sumCoins(arr, 0);
}
public int sumCoins(int[] ar, int sum) {
//if the sum is met, dont add any coins, just return 0
if(sum == S){
return 0;
}
//if the sum is greater, then return max value as it is impossible to get less sum
if(sum > S){
return Integer.MAX_VALUE;
}
//if the array is out of coins return max value
if(ar.length == 0){
return Integer.MAX_VALUE;
}
//if the sum is less than S and there is still more coins to use, keep checking
//add the first coin
int tmpSum = sum + ar[0];
//delete the first coin from the list
int[] tmp = Arrays.copyOfRange(ar, 1, ar.length);
//add one coin to the solution
int one = 1+sumCoins(tmp, tmpSum);
//don't add one coin to the solution
int two = sumCoins(ar,sum);
//see which is more minimized
return Math.min(one,two);
}
Requested Stack Trace:
Exception in thread "main" java.lang.StackOverflowError
at java.lang.Math.min(Math.java:879)
at java.util.Arrays.copyOfRange(Arrays.java:2623)
at Interview.sumCoins(Interview.java:28)
at Interview.sumCoins(Interview.java:32)
at Interview.sumCoins(Interview.java:32)
The answer to this question is in regards to how I was implementing my dynamic programming. I was using the original array in the case where you left the coin. this is incorrect. In more detail:
If you take the coin: get rid of the first (coin) index of the array, add the sum, add +1 for the number of coins.
If you don't take the coin: get rid of the first (coin) index of the array since you're leaving that coin to not be considered.
In my solution, I received a stackoverflow because I was going through the "leaving the coin" scenario infinite times as the array never decreased and I wasn't actually "leaving the coin".
Correct Code here:
private static final int S = 5;
public static int arr[] = {1,1,1,1,1};
public static void main(String[] args) {
Interview i = new Interview();
System.out.println(i.sumCoins(arr, 0));
}
public int sumCoins(int[] ar, int sum) {
//if the sum is met, dont add any coins, just return 0
if(sum == S){
return 0;
}
//if the sum is greater, then return global array (not local)
//length +1 as it's impossible to get more coins than indices
if(sum > S){
return arr.length+1;
}
//if the array is out of coins return max value
if(ar.length == 0){
return arr.length+1;
}
//if the sum is less than S and there is still more coins to use, keep checking
//add the first coin
int tmpSum = sum + ar[0];
//delete the first coin from the list
int[] tmp = Arrays.copyOfRange(ar, 1, ar.length);
//add one coin to the solution
int one = 1+sumCoins(tmp, tmpSum);
//don't add one coin to the solution
int two = sumCoins(tmp,sum);
//see which is more minimized
return Math.min(one,two);
}

Resources