Skip to content
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

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

Closed
wants to merge 1 commit into from
Closed

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

wants to merge 1 commit into from

Conversation

AndyC5H10O5
Copy link

What problem does this PR solve?

In the original code, busy waiting is implemented through an infinite loop and Thread.sleep. This method has the following issues:

  1. Resource waste: Even without expired sessions, threads will continue to run, consuming CPU resources.
  2. Poor scalability: As the number of sessions increases, this method consumes more CPU resources and reduces system performance.
    In the optimized code, busy waiting is replaced by SchechedExecutorService, which executes tasks periodically through event driven methods.

Copy link

sonarcloud bot commented Jul 19, 2024

Comment on lines +92 to +93
synchronized (sessions) {
synchronized (sessionCreationTimes) {
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?

Comment on lines +97 to +99
if (entry.getValue().plusMillis(SESSION_EXPIRATION_TIME).isBefore(currentTime)) {
sessions.remove(entry.getKey());
iterator.remove();
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

}
}).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();
        }
    }));

@AndyC5H10O5 AndyC5H10O5 closed this by deleting the head repository Aug 21, 2024
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants