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 208289
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 11, 20262026-05-11T17:48:43+00:00 2026-05-11T17:48:43+00:00

Referring to Brian Goetz’s article Are all stateful Web applications broken? for IBM developerWorks,

  • 0

Referring to Brian Goetz’s article Are all stateful Web applications broken? for IBM developerWorks, I want to refer to this piece of code

HttpSession session = request.getSession(true);
ShoppingCart cart = (ShoppingCart)session.getAttribute("shoppingCart");
if (cart == null) {
    cart = new ShoppingCart(...);
    session.setAttribute("shoppingCart", cart);
}        
doSomethingWith(cart);

From my available understanding, this code is not thread-safe because it uses the check-then-act pattern. But I have a doubt:

Isn’t the creation or retrieval of the HttpSession in the first line totally atomic? By atomic, I mean that if two Threads call request.getSession(), one will block. Although both will return the same HttpSession instance. Thus, if a client (mobile/web browsers) makes two or make calls to the same Servlet (that executes the snippet above), you will never get a situation in which different threads see different values for cart.

Assuming I am convinced that it is NOT thread safe, how would one make this thread safe? Would an AtomicReference work? e.g.:

HttpSession session = request.getSession(true);
AtomicReference<ShoppingCart> cartRef = 
     (<AtomicReference<ShoppingCart>)session.getAttribute("shoppingCart");
ShoppingCart cart = cartRef.get();
if (cart == null) {
    cart = new ShoppingCart(...);
    session.setAttribute("shoppingCart",
         new AtomicReference<ShoppingCart>(cart));
}
doSomethingWith(cart);

Merci!

  • 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-05-11T17:48:43+00:00Added an answer on May 11, 2026 at 5:48 pm

    Your code is still not Thread-safe:

    ShoppingCart cart = cartRef.get();
    if (cart == null) {
        cart = new ShoppingCart(...);
        session.setAttribute("shoppingCart",
             new AtomicReference<ShoppingCart>(cart));
    }
    

    This is because two Threads can both get a cart of null, create new shopping cart objects, and insert them into the session. One of them will “win,” meaning one will set the object used by future requests, but the other will — for this request — use a totally different cart object.

    To make this Thread-safe, you would need to do something like this, following the idiom from the article you referenced:

    while (true) {
        ShoppingCart cart = cartRef.get();
        if (cart != null) {
            break;
        }
        cart = new ShoppingCart(...);
        if (cartRef.compareAndSet(null, cart))
            break;
    } 
    

    With the above code, if two Threads using the same HttpSession enter the while loop at the same time, there is no data race that can cause them to use different cart objects.

    To address the part of the problem that Brian Goetz doesn’t address in the article, namely how do you get the AtomicReference into the session in the first place, there’s an easy and probably (but not guaranteed) thread-safe way to do this. Namely, implement a session listener and put the empty AtomicReference objects into the session in its sessionCreated method:

    public class SessionInitializer implements HttpSessionListener {
      public void sessionCreated(HttpSessionEvent event){
        HttpSession session = event.getSession();
        session.setAttribute("shoppingCart", new AtomicReference<ShoppingCart>());
      }
      public void sessionDestroyed(HttpSessionEvent event){
        // No special action needed
      }
    }
    

    This method will be called once for each session, only when it is created, so this is an appropriate place to do any initialization that is needed for a session. Unfortunately, the Servlet spec does not require that there is a happens-Before relationship between calling sessionCreated() in your listener and calling your service() method. So this is apparently not guaranteed to be thread safe, and can potentially vary in behavior between different Servlet containers.

    Thus, if there is even a small chance that a given session can have more than one request in flight at a time, this is not safe enough. Ultimately, in this case, you need to use a lock of some sort to initialize the session. You could do something like this:

    HttpSession session = request.getSession(true);
    AtomicReference<ShoppingCart> cartRef;
    // Ensure that the session is initialized
    synchronized (lock) {
        cartRef = (<AtomicReference<ShoppingCart>)session.getAttribute("shoppingCart");
        if (cartRef == null) {
            cartRef = new AtomicReference<ShoppingCart>();
            session.setAttribute("shoppingCart", cartRef);
        }
    }
    

    After the above code has executed, your Session is initialized. The AtomicReference is guaranteed to be in the session, and in a thread-safe manner. You can either update the shopping cart object in the same synchronized block (and dispense with the AtomicReference all together — just put the cart itself into the session), or you can update the AtomicReference with code shown earlier above. Which is better depends on how much initialization you need to do, how long it will take to perform this initialization, on whether doing everything in the synchronized block will hurt performance too much (which is best determined with a profiler, not with a guess), and so on.

    Normally, in my own code, I just use a synchronized block and don’t use Goetz’s AtomicReference trick. If I ever determined that synchronization was causing a liveness problem in my applications, then I would potentially move some more expensive initializations out of synchronized blocks by using tricks like the AtomicReference trick.

    See also: Is HttpSession thread safe, are set/get Attribute thread safe operations?

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

Sidebar

Ask A Question

Stats

  • Questions 130k
  • Answers 130k
  • Best Answers 0
  • User 1
  • Popular
  • Answers
  • Editorial Team

    How to approach applying for a job at a company ...

    • 7 Answers
  • Editorial Team

    How to handle personal stress caused by utterly incompetent and ...

    • 5 Answers
  • Editorial Team

    What is a programmer’s life like?

    • 5 Answers
  • Editorial Team
    Editorial Team added an answer Actually i found the solution. the tableview has a property… May 12, 2026 at 6:09 am
  • Editorial Team
    Editorial Team added an answer I suggest building a Dictionary<string, Operation> to map friendly names… May 12, 2026 at 6:09 am
  • Editorial Team
    Editorial Team added an answer The gist of your question is that you have: template… May 12, 2026 at 6:09 am

Related Questions

Referring to Brian Goetz's article Are all stateful Web applications broken? for IBM developerWorks,
Referring to TLB and maintenance issues ... My question to people (often) using the
referring to my previous question I came accross to another problem. The div I
Referring to my question on filtering ('constraining') types in a foreach loop , I
Referring to this question , how can i get the current page size in

Trending Tags

analytics british company computer developers django employee employer english facebook french google interview javascript language life php programmer programs salary

Top Members

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.