Search code examples
javamultithreadingconcurrencythread-safetysampling

Real time sampling pattern


I have a sensor which receives data at random times at a high frequency and I need a rolling time series window of a specified size (e.g 60 data points) at a specified frequency (e.g 1 data point per second).

The sampled value should be the latest value read from the sensor (i.e all other values between the reads should be discarded).

I assume some sort of producer-consumer pattern is suitable here, but since I lack experience with concurrency I am struggling with a proper and efficient implementation.

When I want to consume all data produced I understand that the ArrayBlockingQueue is a good data structure to choose, but in this case I only want to consume the latest value produced (or if no value is produced, the value of the prior period), and this at exactly a specified frequency (e.g once per second).


Solution

  • Simple answer, use a circular queue.

    //init
    int i = 0; 
    final int N = 60;
    Point[] data=new Point[N];
    for(i=0;i<N;i++)data[i]=new Point();//dummy points to start with
    
    //update
    void addPoint(Point p){
       data[i] = p;
       i = (i+1)%N;
    }
    

    Note that if you don't initialize data properly, the first 60 will be null and you will get NullPointerException. Set them in a loop to some dummy value.

    I should probably explain the code too. The (i+1)%N code will force the number to be between 0 and N-1. When it gets to i=59, then (59+1)%60 = 60 mod 60 = 0. And the cycle continues.