1 year ago

#330472

test-img

Alexei

Can't sync code inside java class Callable

java 8

my snippet:

    private ThreadedApplicationEventPublisher threadedApplicationEventPublisher;
    private final ExecutorService executorService = Executors.newSingleThreadExecutor();
    private final List<Long> failedAttemptsList = new 
LinkedList<>();
    private final Semaphore alarmRaised = new Semaphore(1);
    
            Future<Boolean> future = executorService.submit(new ClearAlarmAndResetAttemptsCallable());
                                
                                    if (future.get().booleanValue()) {
                                       // some code here
                                    }
         //...
        
        
           public class ClearAlarmAndResetAttemptsCallable implements Callable<Boolean> {
    
            @Override
            public Boolean call() throws Exception {
                LOGGER.info("ClearAlarmAndResetAttemptsCallable: start");
                while (true) {
                    long currentTimeSec = System.currentTimeMillis() / 1000;
                    LOGGER.info(
                            "ClearAlarmAndResetAttemptsCallable: in_while, currentTimeSec = {}, failedAttemptsList_size = {}",
                            currentTimeSec, failedAttemptsList.size());
                    synchronized (failedAttemptsList) {
                        LOGGER.info("ClearAlarmAndResetAttemptsCallable: inside_synchronized");
                        Long lastTimeSec = ((LinkedList<Long>) failedAttemptsList).getLast();
                        long durationSec = currentTimeSec - lastTimeSec;
                        if (durationSec > timeWindowSec) {
                            threadedApplicationEventPublisher.publishEvent(new PossibleMCAttackEventPostEvent(this,
                                    folderService.findNetwork(), EventSeverity.NORMAL, DateUtils.getGmtTime(),
                                    AttackTypeEnum.REPETITIVE_FAILED_LOGON_ATTEMPTS, ""));
                            failedAttemptsList.clear();
                            break;
                        }
                    }
                    try {
                        Thread.sleep(timeWindowSec * 100L);
                    } catch (InterruptedException e) {
                        Thread.currentThread().interrupt();
                        break;
                    }
                }
    
                alarmRaised.release();
                return true;
            }
        }

here result log

 ClearAlarmAndResetAttemptsCallable: start
ClearAlarmAndResetAttemptsCallable: in_while, currentTimeSec = 1648120833, failedAttemptsList_size = 3

The question is: Why not print log

ClearAlarmAndResetAttemptsCallable: inside_synchronized

?

java

callable

0 Answers

Your Answer

Accepted video resources