Skip to content

Fix busy-waiting loops for Server Session / App.java #3016

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

Closed
wants to merge 1 commit into from
Closed
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
48 changes: 24 additions & 24 deletions server-session/src/main/java/com/iluwatar/sessionserver/App.java
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,9 @@
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
import lombok.extern.slf4j.Slf4j;

/**
Expand Down Expand Up @@ -75,37 +78,34 @@ public static void main(String[] args) throws IOException {
server.start();

// Start background task to check for expired sessions
sessionExpirationTask();
startSessionExpirationTask();

LOGGER.info("Server started. Listening on port 8080...");
}

private static void sessionExpirationTask() {
new Thread(() -> {
while (true) {
try {
LOGGER.info("Session expiration checker started...");
Thread.sleep(SESSION_EXPIRATION_TIME); // Sleep for expiration time
Instant currentTime = Instant.now();
synchronized (sessions) {
synchronized (sessionCreationTimes) {
Iterator<Map.Entry<String, Instant>> iterator =
sessionCreationTimes.entrySet().iterator();
while (iterator.hasNext()) {
Map.Entry<String, Instant> entry = iterator.next();
if (entry.getValue().plusMillis(SESSION_EXPIRATION_TIME).isBefore(currentTime)) {
sessions.remove(entry.getKey());
iterator.remove();
}
private static void startSessionExpirationTask() {
ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(1);
Runnable sessionExpirationChecker = () -> {
try {
LOGGER.info("Session expiration checker started...");
Instant currentTime = Instant.now();
synchronized (sessions) {
synchronized (sessionCreationTimes) {
Comment on lines +92 to +93
Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Could we use ConcurrentHashMap for sessions and sessionCreationTimes allowing us to remove the need for synchronization blocks?

Iterator<Map.Entry<String, Instant>> iterator = sessionCreationTimes.entrySet().iterator();
while (iterator.hasNext()) {
Map.Entry<String, Instant> entry = iterator.next();
if (entry.getValue().plusMillis(SESSION_EXPIRATION_TIME).isBefore(currentTime)) {
sessions.remove(entry.getKey());
iterator.remove();
Comment on lines +97 to +99
Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Add debug logging for session removal

}
}
}
LOGGER.info("Session expiration checker finished!");
} catch (InterruptedException e) {
LOGGER.error("An error occurred: ", e);
Thread.currentThread().interrupt();
}
LOGGER.info("Session expiration checker finished!");
} catch (Exception e) {
LOGGER.error("An error occurred: ", e);
}
}).start();
};
scheduler.scheduleAtFixedRate(sessionExpirationChecker, 0, SESSION_EXPIRATION_TIME, TimeUnit.MILLISECONDS);
Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

We should also shut down the scheduler when the program exits. Something like this:

Runtime.getRuntime().addShutdownHook(new Thread(() -> {
        scheduler.shutdown();
        try {
            if (!scheduler.awaitTermination(60, TimeUnit.SECONDS)) {
                scheduler.shutdownNow();
            }
        } catch (InterruptedException e) {
            scheduler.shutdownNow();
        }
    }));

}
}
}
Loading