📜 ⬆️ ⬇️

Limit the number of method executions per second

Task : to develop the ability to run a specified number of operations per second.

Requirements :


As a result, I got a function (of course as part of a separate class), which returns true or false (permission to perform).

The general principle is as follows. There is a collection of DateTime time prints (in the comment they suggested that it would be wiser to take Stopwatch). When requesting permission, it is checked whether the number of requests in the last second does not exceed the maximum specified value. If it exceeds, false is returned, otherwise a nugget of the current time is added to the collection and true is returned.
')
Initially, I did everything based on the sheets (List <>), but the sheets have a dynamic data set, which means they are expanded as needed when adding new elements. And it is also necessary to delete. Therefore, I decided to use a collection of a given size. Therefore, I decided to discard the paper in favor of the array. As a result, I got the functionality of a circular collection based on an array, so in the end I made a circular collection.

The result was a pool of date imprints of a given size based on a circular collection. The pool class contains the current item, which has a date stamp and a link to the next item. Initially, all dates have default values.

When requesting permission, the next item from the current item is taken, and 1 second is added to its date. If the date is greater than the current date, then there is no space in the pool and the request returns false. Otherwise, the next element is set as the current element, a date nugget is set in the new current element and the return value is true.

Now about the threads. I didn’t think of anything better than putting lock on the resolution function.

That's all.

For testing, I created a method that performs a specified number of queries with a specified number of threads. Launched it with the following parameters. The number of operations per second is 6, the number of threads is 4, the number of requests is 50.

These results turned out here:



Link to githab

On the screen you can see that the code worked correctly.

Source: https://habr.com/ru/post/331612/


All Articles