Simulating Elderly Checkout Times with ThreadLocalRandom in Java
The article revises a supermarket checkout performance test by incorporating elderly customers who take twice as long to pay, demonstrates using Java's ThreadLocalRandom to randomly assign customer age groups, modifies the pay() method to double payment time for seniors, and explains why realistic scenarios improve testing accuracy.
In the first round of performance testing for a supermarket checkout system, the test only considered young customers, assuming eight cash registers were sufficient for peak traffic. Cashiers pointed out that elderly shoppers take about twice as long to complete payment and represent half of the customers during morning rush hour, prompting a redesign of the test cases.
The article introduces java.util.concurrent.ThreadLocalRandom, a Java class for generating pseudo‑random numbers in multithreaded environments. Unlike java.util.Random, each thread gets its own random number generator, reducing contention and improving performance. The API offers methods to generate int, long, double, and bounded random values, with usage similar to Random.
To model the mixed customer base, the author uses ThreadLocalRandom to produce a random integer 1 or 2, where 1 represents a young customer and 2 represents an elderly customer. This random choice is then used to adjust the simulated payment time.
/**
* 支付
*/
public void pay(){
// 顾客支付阶段
int milliseconds = (int) (System.currentTimeMillis() % 10000) / 100;
int i = ThreadLocalRandom.current().nextInt(2) + 1; // 随机生成1或2
ThreadTool.sleep(milliseconds * i); // 如果是老年人,支付时间翻倍
}By multiplying the base sleep time by the random factor i, the method doubles the payment duration when the simulated customer is elderly. This adjustment makes the test scenario more realistic, reflecting the actual mix of young and senior shoppers.
After updating the test case, the author reruns the performance test, expecting more accurate results that better inform capacity planning and system tuning. The narrative emphasizes that technical work should serve real user needs rather than chasing abstract efficiency metrics.
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
