Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • Home
  • SEARCH
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 8307007
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 8, 20262026-06-08T18:26:35+00:00 2026-06-08T18:26:35+00:00

I have the following code: private static HashSet<SoloUser> soloUsers = new HashSet<SoloUser>(); public void

  • 0

I have the following code:

private static HashSet<SoloUser> soloUsers = new HashSet<SoloUser>();

    public void findNewPartner(string School, string Major)
    {
        lock (soloUsers)
        {
            SoloUser soloUser = soloUsers.FirstOrDefault(s => (s.School == School) && (s.Major == Major));
            MatchConnection matchConn;
            if (soloUser != null)
            {
                if (soloUser.ConnectionId != Context.ConnectionId)
                {                                                                     
                    soloUsers.Remove(soloUser);
                }

            }
            else
            {   string sessionId = TokenHelper.GenerateSession();                                     

                soloUser = new SoloUser
                {
                    Major = Major,
                    School = School,
                    SessionId = sessionId,
                    ConnectionId = Context.ConnectionId
                };

                soloUsers.Add(soloUser);


            }

        } 

    }

TokenHelper.GenerateToken(soloUser.Session) and TokenHelper.GenerateModeratorToken(session); could be hazardous because they may take a moment to generate a token. This will lock all users out for a that moment which could be a problem? Are there any workarounds to this logic so that I can still keep everything threadsafe?

EDIT:
I removed the TokenHelper.GenerateToken(soloUser.Session) and TokenHelper.GenerateModeratorToken(session) because I realized they can happen outside of the lock, but each SoloUser has a property called SessionId and this is generated for each user. the GenerateSession method would also be a method that takes a moment. Each user needs to have one of these SessionIds before being added to the collection

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-06-08T18:26:38+00:00Added an answer on June 8, 2026 at 6:26 pm

    You can move the GenerateSession out of the lock if you can afford to take the lock twice and if it’s ok if occasionally a sessionId is generated but never used.

    Something like this:

     public void findNewPartner(string School, string Major)
        {
            SoloUser soloUser = null;
    
            lock (soloUsers)
            {
                soloUser = soloUsers.FirstOrDefault(s => (s.School == School) && (s.Major == Major));
            }
    
            string sessionId = null;
    
            // will we be creating a new soloUser?
            if (soloUser == null)
            { 
                // then we'll need a new session for that new user
                sessionId = TokenHelper.GenerateSession();
            }
    
            lock (soloUsers)
            {
                soloUser = soloUsers.FirstOrDefault(s => (s.School == School) && (s.Major == Major));
                if (soloUser != null)
                {
                    // woops! Guess we don't need that sessionId after all.  Oh well! Carry on...
                    if (soloUser.ConnectionId != Context.ConnectionId)
                    {                                                                     
                        soloUsers.Remove(soloUser);
                    }
    
                }
                else
                {   
                    // use the sessionid computed earlier
                    soloUser = new SoloUser
                    {
                        Major = Major,
                        School = School,
                        SessionId = sessionId,
                        ConnectionId = Context.ConnectionId
                    };
    
                    soloUsers.Add(soloUser);
    
            }
    
        } 
    

    This basically does a quick lock to see if a new soloUser needs to be constructed and if so, then we need to generate a new session. Generating the new session happens outside the lock. We then reaquire the lock and perform the original set of operations. When constructing a new soloUser, it uses the sessionId that was constructed outside the lock.

    This pattern could generate sessionIds that are never used. If two threads execute this function at the same time with the same school and major, both threads will generated session ids, but only one of the threads will successfully create a new soloUser and add it to the collection. The losing thread will find the soloUser in the collection and remove it from the collection – and not use the sessionId it just generated. At this point, both threads will be referring to the same soloUser with the same sessionId, which appears to be the goal.

    If sessionIds have resources associated with them (such as an entry in a database) but these resources will be cleaned up when the sessionId ages out, then collisions like this will produce a little extra noise but overall should not impact the system.

    If the generated sessionIds have nothing associated with them that would require clean up or aging out, then you might consider losing the first lock in my example and just always generate a sessionId, whether it’s needed or not. This is probably not a likely scenario, but I have used this sort of “promiscuous” trick in specialized cases before to avoid hopping in and out of high traffic locks. If it’s cheap to create and expensive to lock, then create with abandon and be careful with the locks.

    Make sure the cost of GenerateSession is high enough to justify this extra run-around. If GenerateSession takes nanoseconds to complete, you don’t need all this – just leave it in the lock as originally written. If GenerateSession takes “a long time” (a second or more? 500ms or more? can’t say), then moving it out of the lock is a good idea to prevent other uses of the shared list from having to wait.

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I have the following code: public static void main(String[] args) { willItThrowException(); } private
I have the following code: private String foo; public void setFoo(String bar) { foo
Consider the following code: private static BackgroundWorker bg = new BackgroundWorker(); static void Main(string[]
I have the following code - private static void convert() { string csv =
I have the following code public class Test{ private static final String key =
I have the following code: private static final Set<String> allowedParameters; static { Set<String> tmpSet
I have the following code: public partial class queryTerm : System.Web.UI.UserControl { private static
I have the following code: public class Test extends JFrame implements ActionListener{ private static
I have the following code: private void _DoValidate(object sender, DoWorkEventArgs e) { this.BeginInvoke(new MethodInvoker(()
I have the following code private Map<KEY, Object> values = new HashMap<KEY, Object>(); public

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.