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

Mutithreading issues in cognitoIdentity CognitoUser #272

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
Original file line number Diff line number Diff line change
Expand Up @@ -99,7 +99,7 @@
import java.util.Locale;
import java.util.Map;
import java.util.TimeZone;

import java.util.concurrent.Semaphore;
/**
* Represents a single Cognito User.
* <p>
Expand Down Expand Up @@ -163,6 +163,11 @@ public class CognitoUser {
*/
private CognitoUserSession cipSession;

/**
* The semaphore to provide mutex for the getSession call if called on multiple threads, this would avoid multiple threads going over the network and refreshing the tokens
*/
public static Semaphore semaphore = new Semaphore(1, true);
Copy link
Contributor

Choose a reason for hiding this comment

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

Is there a reason this is public? If not please change to private.


/**
* Constructs a new Cognito User from a Cognito user identity pool {@link CognitoUserPool} and userId.
*
Expand Down Expand Up @@ -708,7 +713,12 @@ protected CognitoUserSession getCachedSession() {
return cipSession;
}
}

try {
CognitoUser.semaphore.acquire();
} catch (InterruptedException e) {
e.printStackTrace();
}

CognitoUserSession cachedTokens = readCachedTokens();

if (cachedTokens.isValidForThreshold()) {
Expand All @@ -720,11 +730,14 @@ protected CognitoUserSession getCachedSession() {
try {
cipSession = refreshSession(cachedTokens);
cacheTokens(cipSession);
CognitoUser.semaphore.release();
return cipSession;
} catch (NotAuthorizedException nae) {
clearCachedTokens();
CognitoUser.semaphore.release();
throw new CognitoNotAuthorizedException("User is not authenticated", nae);
} catch (Exception e) {
CognitoUser.semaphore.release();
Copy link
Contributor

Choose a reason for hiding this comment

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

Since we are dealing with locking here, can you move the release into a finally block?

throw new CognitoInternalErrorException("Failed to authenticate user", e);
}
}
Expand Down