RetryAspect exceeding maximum retry attempts in Java AOP

I’m encountering a problem with a custom RetryAspect implementation using Java AOP, where the retry logic exceeds the maximum attempts configured. Here’s the scenario and the current implementation details:

Scenario:

I have implemented a custom RetryAspect to retry methods annotated with @Retryable. The aspect is supposed to retry the method execution a maximum of 3 times (maxAttempts = 3) if certain exceptions are thrown.

Code Details:

Here’s my RetryAspect implementation:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code> import com.annotations.Retryable;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
@Aspect
public class RetryAspect {
final Object lock = new Object();
@Pointcut("@annotation(retryable)")
public void retryableMethods(Retryable retryable) {
}
@Around(value = "retryableMethods(retryable)", argNames = "joinPoint,retryable")
public Object retryMethod(ProceedingJoinPoint joinPoint, Retryable retryable) throws Throwable {
int maxAttempts = retryable.maxAttempts();
long delay = retryable.backoff().delay();
Throwable lastException = null;
synchronized (lock) {
for (int attempt = 1; attempt <= maxAttempts; attempt++) {
try {
System.out.println("Attempt " + attempt + " of " + maxAttempts);
return joinPoint.proceed();
} catch (Throwable ex) {
System.out.println("Caught exception: " + ex.getClass().getSimpleName());
if (isExceptionIncluded(ex, retryable.include())) {
lastException = ex;
if (attempt < maxAttempts) {
System.out.println("Sleeping for " + delay + "ms before retry");
Thread.sleep(delay);
}
} else {
System.out.println("Exception " + ex.getClass().getSimpleName() + " is not included in retryable.include(). Rethrowing...");
throw ex; // Rethrow the exception since it's not retryable
}
}
}
// If we reach here, maxAttempts is exceeded
System.out.println("Max attempts exceeded (" + maxAttempts + "). Throwing last exception.");
throw lastException != null ? lastException : new RuntimeException("Retry failed after max attempts");
}
}
private boolean isExceptionIncluded(Throwable ex, Class<? extends Throwable>[] includedClasses) {
for (Class<? extends Throwable> includedClass : includedClasses) {
if (includedClass.isInstance(ex)) {
return true;
}
}
return false;
}
}
</code>
<code> import com.annotations.Retryable; import org.aspectj.lang.ProceedingJoinPoint; import org.aspectj.lang.annotation.Around; import org.aspectj.lang.annotation.Aspect; import org.aspectj.lang.annotation.Pointcut; @Aspect public class RetryAspect { final Object lock = new Object(); @Pointcut("@annotation(retryable)") public void retryableMethods(Retryable retryable) { } @Around(value = "retryableMethods(retryable)", argNames = "joinPoint,retryable") public Object retryMethod(ProceedingJoinPoint joinPoint, Retryable retryable) throws Throwable { int maxAttempts = retryable.maxAttempts(); long delay = retryable.backoff().delay(); Throwable lastException = null; synchronized (lock) { for (int attempt = 1; attempt <= maxAttempts; attempt++) { try { System.out.println("Attempt " + attempt + " of " + maxAttempts); return joinPoint.proceed(); } catch (Throwable ex) { System.out.println("Caught exception: " + ex.getClass().getSimpleName()); if (isExceptionIncluded(ex, retryable.include())) { lastException = ex; if (attempt < maxAttempts) { System.out.println("Sleeping for " + delay + "ms before retry"); Thread.sleep(delay); } } else { System.out.println("Exception " + ex.getClass().getSimpleName() + " is not included in retryable.include(). Rethrowing..."); throw ex; // Rethrow the exception since it's not retryable } } } // If we reach here, maxAttempts is exceeded System.out.println("Max attempts exceeded (" + maxAttempts + "). Throwing last exception."); throw lastException != null ? lastException : new RuntimeException("Retry failed after max attempts"); } } private boolean isExceptionIncluded(Throwable ex, Class<? extends Throwable>[] includedClasses) { for (Class<? extends Throwable> includedClass : includedClasses) { if (includedClass.isInstance(ex)) { return true; } } return false; } } </code>
    import com.annotations.Retryable;
    import org.aspectj.lang.ProceedingJoinPoint;
    import org.aspectj.lang.annotation.Around;
    import org.aspectj.lang.annotation.Aspect;
    import org.aspectj.lang.annotation.Pointcut;
    @Aspect
    public class RetryAspect {
    
        final Object lock = new Object();
    
        @Pointcut("@annotation(retryable)")
        public void retryableMethods(Retryable retryable) {
        }
    
        @Around(value = "retryableMethods(retryable)", argNames = "joinPoint,retryable")
        public Object retryMethod(ProceedingJoinPoint joinPoint, Retryable retryable) throws Throwable {
            int maxAttempts = retryable.maxAttempts();
            long delay = retryable.backoff().delay();
    
            Throwable lastException = null;
    
            synchronized (lock) {
                for (int attempt = 1; attempt <= maxAttempts; attempt++) {
                    try {
                        System.out.println("Attempt " + attempt + " of " + maxAttempts);
                        return joinPoint.proceed();
                    } catch (Throwable ex) {
                        System.out.println("Caught exception: " + ex.getClass().getSimpleName());
                        if (isExceptionIncluded(ex, retryable.include())) {
                            lastException = ex;
                            if (attempt < maxAttempts) {
                                System.out.println("Sleeping for " + delay + "ms before retry");
                                Thread.sleep(delay);
                            }
                        } else {
                            System.out.println("Exception " + ex.getClass().getSimpleName() + " is not included in retryable.include(). Rethrowing...");
                            throw ex; // Rethrow the exception since it's not retryable
                        }
                    }
                }
    
                // If we reach here, maxAttempts is exceeded
                System.out.println("Max attempts exceeded (" + maxAttempts + "). Throwing last exception.");
                throw lastException != null ? lastException : new RuntimeException("Retry failed after max attempts");
            }
        }
    
        private boolean isExceptionIncluded(Throwable ex, Class<? extends Throwable>[] includedClasses) {
            for (Class<? extends Throwable> includedClass : includedClasses) {
                if (includedClass.isInstance(ex)) {
                    return true;
                }
            }
            return false;
        }
    }

Here’s my ExampleService implementation:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code>public class ExampleService {
@Retryable(maxAttempts = 3, backoff = @Backoff(delay = 500), include = RetryException.class)
public void retryableMethod() throws RetryException {
System.out.println("Executing retryableMethod...");
throw new RetryException("Simulated Exception");
}
}
</code>
<code>public class ExampleService { @Retryable(maxAttempts = 3, backoff = @Backoff(delay = 500), include = RetryException.class) public void retryableMethod() throws RetryException { System.out.println("Executing retryableMethod..."); throw new RetryException("Simulated Exception"); } } </code>
public class ExampleService {

    @Retryable(maxAttempts = 3, backoff = @Backoff(delay = 500), include = RetryException.class)
    public void retryableMethod() throws RetryException {
        System.out.println("Executing retryableMethod...");
        throw new RetryException("Simulated Exception");
    }
}

Problem:

However, during testing, I noticed that the retry logic continues beyond 3 attempts. Here’s the output I’m observing:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code>Attempt 1 of 3
Attempt 1 of 3
Executing retryableMethod...
Caught exception: RetryException
Sleeping for 500ms before retry
Attempt 2 of 3
Executing retryableMethod...
Caught exception: RetryException
Sleeping for 500ms before retry
Attempt 3 of 3
Executing retryableMethod...
Caught exception: RetryException
Max attempts exceeded (3). Throwing last exception.
Caught exception: RetryException
Sleeping for 500ms before retry
Attempt 2 of 3
Attempt 1 of 3
Executing retryableMethod...
Caught exception: RetryException
Sleeping for 500ms before retry
Attempt 2 of 3
Executing retryableMethod...
Caught exception: RetryException
Sleeping for 500ms before retry
Attempt 3 of 3
Executing retryableMethod...
Caught exception: RetryException
Max attempts exceeded (3). Throwing last exception.
Caught exception: RetryException
Sleeping for 500ms before retry
Attempt 3 of 3
Attempt 1 of 3
Executing retryableMethod...
Caught exception: RetryException
Sleeping for 500ms before retry
Attempt 2 of 3
Executing retryableMethod...
Caught exception: RetryException
Sleeping for 500ms before retry
Attempt 3 of 3
Executing retryableMethod...
Caught exception: RetryException
Max attempts exceeded (3). Throwing last exception.
Caught exception: RetryException
Max attempts exceeded (3). Throwing last exception.
</code>
<code>Attempt 1 of 3 Attempt 1 of 3 Executing retryableMethod... Caught exception: RetryException Sleeping for 500ms before retry Attempt 2 of 3 Executing retryableMethod... Caught exception: RetryException Sleeping for 500ms before retry Attempt 3 of 3 Executing retryableMethod... Caught exception: RetryException Max attempts exceeded (3). Throwing last exception. Caught exception: RetryException Sleeping for 500ms before retry Attempt 2 of 3 Attempt 1 of 3 Executing retryableMethod... Caught exception: RetryException Sleeping for 500ms before retry Attempt 2 of 3 Executing retryableMethod... Caught exception: RetryException Sleeping for 500ms before retry Attempt 3 of 3 Executing retryableMethod... Caught exception: RetryException Max attempts exceeded (3). Throwing last exception. Caught exception: RetryException Sleeping for 500ms before retry Attempt 3 of 3 Attempt 1 of 3 Executing retryableMethod... Caught exception: RetryException Sleeping for 500ms before retry Attempt 2 of 3 Executing retryableMethod... Caught exception: RetryException Sleeping for 500ms before retry Attempt 3 of 3 Executing retryableMethod... Caught exception: RetryException Max attempts exceeded (3). Throwing last exception. Caught exception: RetryException Max attempts exceeded (3). Throwing last exception. </code>
Attempt 1 of 3
Attempt 1 of 3
Executing retryableMethod...
Caught exception: RetryException
Sleeping for 500ms before retry
Attempt 2 of 3
Executing retryableMethod...
Caught exception: RetryException
Sleeping for 500ms before retry
Attempt 3 of 3
Executing retryableMethod...
Caught exception: RetryException
Max attempts exceeded (3). Throwing last exception.
Caught exception: RetryException
Sleeping for 500ms before retry
Attempt 2 of 3
Attempt 1 of 3
Executing retryableMethod...
Caught exception: RetryException
Sleeping for 500ms before retry
Attempt 2 of 3
Executing retryableMethod...
Caught exception: RetryException
Sleeping for 500ms before retry
Attempt 3 of 3
Executing retryableMethod...
Caught exception: RetryException
Max attempts exceeded (3). Throwing last exception.
Caught exception: RetryException
Sleeping for 500ms before retry
Attempt 3 of 3
Attempt 1 of 3
Executing retryableMethod...
Caught exception: RetryException
Sleeping for 500ms before retry
Attempt 2 of 3
Executing retryableMethod...
Caught exception: RetryException
Sleeping for 500ms before retry
Attempt 3 of 3
Executing retryableMethod...
Caught exception: RetryException
Max attempts exceeded (3). Throwing last exception.
Caught exception: RetryException
Max attempts exceeded (3). Throwing last exception.

Expected Behavior:
The retry logic should attempt the method execution up to 3 times and throw the last exception when maxAttempts is reached. However, it currently retries beyond the configured limit.

Additional Information:
Java version: 17

I’ve tried adjusting the loop structure and ensuring proper exception handling, but I haven’t been successful in limiting the retry attempts. Any insights or suggestions on how to correct this behavior would be greatly appreciated. Thank you!

Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa Dịch vụ tổ chức sự kiện 5 sao Thông tin về chúng tôi Dịch vụ sinh nhật bé trai Dịch vụ sinh nhật bé gái Sự kiện trọn gói Các tiết mục giải trí Dịch vụ bổ trợ Tiệc cưới sang trọng Dịch vụ khai trương Tư vấn tổ chức sự kiện Hình ảnh sự kiện Cập nhật tin tức Liên hệ ngay Thuê chú hề chuyên nghiệp Tiệc tất niên cho công ty Trang trí tiệc cuối năm Tiệc tất niên độc đáo Sinh nhật bé Hải Đăng Sinh nhật đáng yêu bé Khánh Vân Sinh nhật sang trọng Bích Ngân Tiệc sinh nhật bé Thanh Trang Dịch vụ ông già Noel Xiếc thú vui nhộn Biểu diễn xiếc quay đĩa Dịch vụ tổ chức tiệc uy tín Khám phá dịch vụ của chúng tôi Tiệc sinh nhật cho bé trai Trang trí tiệc cho bé gái Gói sự kiện chuyên nghiệp Chương trình giải trí hấp dẫn Dịch vụ hỗ trợ sự kiện Trang trí tiệc cưới đẹp Khởi đầu thành công với khai trương Chuyên gia tư vấn sự kiện Xem ảnh các sự kiện đẹp Tin mới về sự kiện Kết nối với đội ngũ chuyên gia Chú hề vui nhộn cho tiệc sinh nhật Ý tưởng tiệc cuối năm Tất niên độc đáo Trang trí tiệc hiện đại Tổ chức sinh nhật cho Hải Đăng Sinh nhật độc quyền Khánh Vân Phong cách tiệc Bích Ngân Trang trí tiệc bé Thanh Trang Thuê dịch vụ ông già Noel chuyên nghiệp Xem xiếc khỉ đặc sắc Xiếc quay đĩa thú vị
Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa
Thiết kế website Thiết kế website Thiết kế website Cách kháng tài khoản quảng cáo Mua bán Fanpage Facebook Dịch vụ SEO Tổ chức sinh nhật