0

My code stores the transactions for each 60 sec in a List and then the list is cleaned using Scheduler:

@Configuration
@EnableScheduling
@EnableAsync

@Slf4j
public class ApplicationConfig {


    @Async
    @Scheduled(fixedDelay = 60 * 1000, initialDelay = 60 * 1000)
    public void scheduleTransactionClearance() {

        log.info("Performing the clearance the transactions in each 60 sec from the storage");
        TransactionCollectors.getTransactionList().clear();
    }

}

An integration test use Thread.sleep(5000) so then I try to get the statistics, I have the transactions for 1 min and 5 sec. I correct the code to manually check and delete if any transactions are older than 60 sec:

private void deleteOlderTransaction(List<Transaction> transactions) {

        final int initialTransactionsSize = transactions.size();

        final boolean isOlderTransactionsDeleted = transactions.removeIf(tx -> Duration.between(tx.getLocalDateTime(), LocalDateTime.now(ZoneOffset.UTC)).toSeconds() >= 60);

        if (isOlderTransactionsDeleted) {

            log.info("we have deleted translations that are older than 60 seconds and the deleted transactions count =" + (initialTransactionsSize - transactions.size()));
        }
    }

However, this situation may arrive only once and I don't need to make this call for each time which is unnecessary and code looks bad as well.

Is there any way to know if the Thread.sleep is called and based on that condition we can run the scheduler?

Also is there any way I can check from a method that the current thread is just awake from sleep and if true, I will try to delete the older transactions if any?

Arefe
  • 11,321
  • 18
  • 114
  • 168
  • Don't... use a proper caching framework which does all this for you, you are basically trying to write your own caching solution, which might look simply but it really isn't. – M. Deinum Apr 16 '21 at 07:17
  • @M.Deinum This is very helpful as can be done with `CacheEvict` – Arefe Apr 16 '21 at 07:27
  • 1
    You don't need `CacheEvict`. You just need to configure your caching to hold elements for 60 seconds. The caching will handle everything else, transparently. – M. Deinum Apr 16 '21 at 08:31
  • This is answer the question: https://stackoverflow.com/questions/64059670/spring-boot-evicting-cache-with-dynamic-ttl-period and https://stackoverflow.com/questions/8181768/can-i-set-a-ttl-for-cacheable – Arefe Apr 19 '21 at 04:13

0 Answers0