Video tayyorlanmoqda

Senior 🧪 Testlash

Ikki parallel so'rov bir kuponni ikki marta ishlatib yuborishi mumkin. Bazadagi bunday race'ni integratsion testda qanday qayta hosil qilasiz?

@Transactional
public void redeem(String code, long userId) {
    Coupon c = couponRepo.findByCode(code).orElseThrow();
    if (c.getUsed() >= c.getLimit()) throw new CouponExhaustedException();
    c.setUsed(c.getUsed() + 1);
    redemptionRepo.save(new Redemption(c, userId));
}

Bir nechta thread'ni CountDownLatch bilan bir vaqtda "start"ga qo'yib, bir xil operatsiyani haqiqiy baza ustida parallel chaqiraman va invariantni tekshiraman: kupon bir marta ishlatilgan bo'lishi kerak. Testni ko'p iteratsiya bilan ishga tushiraman, chunki race har safar chiqmaydi.

📖 Javob

Bu kodda klassik "read-modify-write" race bor: ikki transaction used = 0'ni bir vaqtda o'qiydi, ikkalasi ham tekshiruvdan o'tadi, ikkalasi ham used = 1 yozadi — limit 1 bo'lgan kupon ikki marta ishlatildi.

Test:

@Test
void couponCannotBeRedeemedTwiceConcurrently() throws Exception {
    String code = saveCoupon(limit(1)).getCode();
    int threads = 8;
    var start = new CountDownLatch(1);
    var pool = Executors.newFixedThreadPool(threads);
    List<Future<Boolean>> results = new ArrayList<>();

    for (int i = 0; i < threads; i++) {
        long userId = i;
        results.add(pool.submit(() -> {
            start.await();
            try { couponService.redeem(code, userId); return true; }
            catch (CouponExhaustedException | ObjectOptimisticLockingFailureException e) { return false; }
        }));
    }
    start.countDown();
    long ok = 0;
    for (Future<Boolean> f : results) if (f.get(5, SECONDS)) ok++;   // f.get() checked exception tashlaydi; test metodi throws Exception e'lon qilgan

    assertThat(ok).isEqualTo(1);
    assertThat(redemptionRepo.countByCouponCode(code)).isEqualTo(1);
}

Muhim shartlar: test o'zi @Transactional bo'lmasin (aks holda thread'lar boshqa transaction'larda ma'lumotni ko'rmaydi), baza haqiqiy bo'lsin (H2'ning lock xatti-harakati boshqa), va testni @RepeatedTest(20) bilan ishga tushiring.

Tuzatish variantlari: @Version bilan optimistic lock, SELECT ... FOR UPDATE, yoki bitta atomik UPDATE coupon SET used = used + 1 WHERE code = ? AND used < limit_count va o'zgargan qatorlar sonini tekshirish. Oxirgisi eng sodda va tez.

Pastroq darajadagi lock-free kod uchun (o'z ConcurrentHashMap o'rami, AtomicLong mantiqi) jcstress kabi maxsus vosita bor — u memory model darajasidagi muammolarni topadi, oddiy JUnit testi buni ko'rmaydi.