-
Notifications
You must be signed in to change notification settings - Fork 0
refacto: make async persisting logic more readable and maintainable #155
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
GhilesA
wants to merge
1
commit into
main
Choose a base branch
from
refacto/improve_persisted_poller_code
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
114 changes: 114 additions & 0 deletions
114
src/main/java/org/gridsuite/sensitivityanalysis/server/util/BatchAsyncPoller.java
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,114 @@ | ||
| /** | ||
| * Copyright (c) 2026, RTE (http://www.rte-france.com) | ||
| * This Source Code Form is subject to the terms of the Mozilla Public | ||
| * License, v. 2.0. If a copy of the MPL was not distributed with this | ||
| * file, You can obtain one at http://mozilla.org/MPL/2.0/. | ||
| */ | ||
| package org.gridsuite.sensitivityanalysis.server.util; | ||
|
|
||
| import lombok.extern.slf4j.Slf4j; | ||
|
|
||
| import java.util.ArrayList; | ||
| import java.util.List; | ||
| import java.util.UUID; | ||
| import java.util.concurrent.*; | ||
| import java.util.concurrent.atomic.AtomicBoolean; | ||
| import java.util.function.BiConsumer; | ||
|
|
||
| /** | ||
| * @author Ghiles Abdellah {@literal <ghiles.abdellah at rte-france.com>} | ||
| */ | ||
| @Slf4j | ||
| public class BatchAsyncPoller<T> { | ||
|
|
||
| protected static final int BUFFER_SIZE = 512; | ||
| private static final int TASK_INITIAL_DELAY = 0; | ||
| private static final int TASK_DELAY = 100; | ||
|
|
||
| private final UUID resultUuid; | ||
| private final String taskName; | ||
| private final AtomicBoolean isProducerFinished; | ||
| private final BiConsumer<UUID, List<T>> batchHandlingFunction; | ||
|
|
||
| private final BlockingQueue<T> blockingQueue; | ||
| private final ScheduledFuture<?> pollingFuture; | ||
|
|
||
| public BatchAsyncPoller(ScheduledExecutorService scheduledExecutorService, UUID resultUuid, | ||
| String taskName, BiConsumer<UUID, List<T>> batchHandlingFunction) { | ||
| this.resultUuid = resultUuid; | ||
| this.taskName = taskName; | ||
| this.batchHandlingFunction = batchHandlingFunction; | ||
| this.isProducerFinished = new AtomicBoolean(false); | ||
|
|
||
| this.blockingQueue = new LinkedBlockingQueue<>(); | ||
| this.pollingFuture = scheduledExecutorService.scheduleWithFixedDelay(this::drainQueue, TASK_INITIAL_DELAY, TASK_DELAY, TimeUnit.MILLISECONDS); | ||
| } | ||
|
|
||
| public void add(T data) { | ||
| // we check for : | ||
| // - pollingFuture.isDone() -> avoid storing data that will never be processed | ||
| // - isProducerFinished.get() -> since the producer is finished, the rest of the code can stop the data consumption at any given time | ||
| if (pollingFuture.isDone() || isProducerFinished.get()) { | ||
| throw new IllegalStateException("Cannot add data to a finished Poller"); | ||
| } | ||
|
|
||
| blockingQueue.add(data); | ||
| } | ||
|
|
||
| public void notifyCompletion() { | ||
| isProducerFinished.set(true); | ||
| } | ||
|
|
||
| /** | ||
| * @throws InterruptedException - if the current thread was interrupted while waiting | ||
| * @throws ExecutionException - if one scheduled iteration failed | ||
| * @throws CancellationException - if the scheduled task was canceled abruptly | ||
| */ | ||
| public void waitForCompletion() throws InterruptedException, ExecutionException, CancellationException { | ||
| try { | ||
| pollingFuture.get(); | ||
| } catch (CancellationException e) { | ||
| // Since CancellationException can be triggered either: | ||
| // - by the scheduler when the thread is interrupted, or | ||
| // - by the composition producer+consumer is finished, | ||
| // we need to check if the producer has finished | ||
| if (!hasFullyConsumedData()) { | ||
| throw e; | ||
| } | ||
| } | ||
| } | ||
|
|
||
| /** | ||
| * This method makes exceptions bubble if the `batchHandlingFunction` throws one. | ||
| * The goal is to stop the unnecessary consumption and allow the calling code to know that the process failed at one point. | ||
| * The scheduler will stop it and mark the future with an exception -> a call to `waitForCompletion` will then throw an `ExecutionException` | ||
| */ | ||
| private void drainQueue() { | ||
| List<T> buffer = new ArrayList<>(BUFFER_SIZE); | ||
|
|
||
| while (!shouldStop() && hasDrainedData(buffer)) { | ||
| log.debug("{} - Treating {} elements in the batch, {} elements remaining in the queue", taskName, buffer.size(), blockingQueue.size()); | ||
| batchHandlingFunction.accept(resultUuid, new ArrayList<>(buffer)); | ||
| buffer.clear(); | ||
| } | ||
|
|
||
| if (shouldStop()) { | ||
| pollingFuture.cancel(false); | ||
| } | ||
| } | ||
|
|
||
| private boolean shouldStop() { | ||
| // Thread.currentThread().isInterrupted() check is mandatory for the loop since it doesn't have method calls that checks the flag | ||
| // hasFullyConsumedData() is also mandatory given the logic inside the calling method | ||
| // it allows to consume all data before leaving the calling loop (full drain) | ||
| return Thread.currentThread().isInterrupted() || hasFullyConsumedData(); | ||
| } | ||
|
|
||
| private boolean hasFullyConsumedData() { | ||
| return isProducerFinished.get() && blockingQueue.isEmpty(); | ||
| } | ||
|
|
||
| private boolean hasDrainedData(List<T> buffer) { | ||
| return blockingQueue.drainTo(buffer, BUFFER_SIZE) > 0; | ||
| } | ||
| } |
27 changes: 27 additions & 0 deletions
27
src/main/java/org/gridsuite/sensitivityanalysis/server/util/BatchAsyncPollerFactory.java
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,27 @@ | ||
| /** | ||
| * Copyright (c) 2026, RTE (http://www.rte-france.com) | ||
| * This Source Code Form is subject to the terms of the Mozilla Public | ||
| * License, v. 2.0. If a copy of the MPL was not distributed with this | ||
| * file, You can obtain one at http://mozilla.org/MPL/2.0/. | ||
| */ | ||
| package org.gridsuite.sensitivityanalysis.server.util; | ||
|
|
||
| import java.util.List; | ||
| import java.util.UUID; | ||
| import java.util.concurrent.ScheduledExecutorService; | ||
| import java.util.function.BiConsumer; | ||
|
|
||
| /** | ||
| * @author Ghiles Abdellah {@literal <ghiles.abdellah at rte-france.com>} | ||
| */ | ||
GhilesA marked this conversation as resolved.
Show resolved
Hide resolved
|
||
| public final class BatchAsyncPollerFactory { | ||
|
|
||
| public static BatchAsyncPollerFactory getDefault() { | ||
| return new BatchAsyncPollerFactory(); | ||
| } | ||
|
|
||
| public <T> BatchAsyncPoller<T> create(ScheduledExecutorService scheduledExecutorService, UUID resultUuid, | ||
| String taskName, BiConsumer<UUID, List<T>> batchHandlingFunction) { | ||
| return new BatchAsyncPoller<>(scheduledExecutorService, resultUuid, taskName, batchHandlingFunction); | ||
| } | ||
| } | ||
35 changes: 35 additions & 0 deletions
35
src/main/java/org/gridsuite/sensitivityanalysis/server/util/ScheduledThreadPoolFactory.java
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,35 @@ | ||
| /** | ||
| * Copyright (c) 2026, RTE (http://www.rte-france.com) | ||
| * This Source Code Form is subject to the terms of the Mozilla Public | ||
| * License, v. 2.0. If a copy of the MPL was not distributed with this | ||
| * file, You can obtain one at http://mozilla.org/MPL/2.0/. | ||
| */ | ||
| package org.gridsuite.sensitivityanalysis.server.util; | ||
|
|
||
| import com.google.common.util.concurrent.ThreadFactoryBuilder; | ||
|
|
||
| import java.util.Objects; | ||
| import java.util.UUID; | ||
| import java.util.concurrent.Executors; | ||
| import java.util.concurrent.ScheduledExecutorService; | ||
| import java.util.concurrent.ThreadFactory; | ||
|
|
||
| /** | ||
| * @author Ghiles Abdellah {@literal <ghiles.abdellah at rte-france.com>} | ||
| */ | ||
| public final class ScheduledThreadPoolFactory { | ||
|
|
||
| public static ScheduledThreadPoolFactory getDefault() { | ||
| return new ScheduledThreadPoolFactory(); | ||
| } | ||
|
|
||
| public ScheduledExecutorService create(int size, UUID threadPrefix) { | ||
| Objects.requireNonNull(threadPrefix); | ||
|
|
||
| ThreadFactory factory = new ThreadFactoryBuilder() | ||
| .setNameFormat(threadPrefix + "-%d") | ||
| .setDaemon(false) | ||
| .build(); | ||
| return Executors.newScheduledThreadPool(size, factory); | ||
| } | ||
| } |
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.