8.04.2009

Synchronizing the HttpSession

This is something that I have heard a great deal of debate over the last 2 years about. The servlet spec was somewhat recently amended to clarify that there is no guarantee that multiple calls to HttpServletRequest.getSession() or HttpServletRequest.getSession(boolean) will return the same object. This holds especially true in containers that return a facade object that wraps around the actual HttpSession object that you are working with, like Tomcat.

Why would you want to synchronize a session anyway?
The answer is pretty simple actually. Consider the following theoretical block of code:

public class WithdrawFundsServlet extends HttpServlet {

@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
User u = ESAPI.authenticator().getCurrentUser();
String withdrawAmt = request.getParameter("withdrawAmt");
float amt;
Account acct = session.getAttribute("acct_"+u.getAccount());
try
{
amt = Float.parseFloat(withdrawAmt);
}
catch ( Throwable t )
{
ESAPI.log().info( Logger.SECURITY_FAILURE, "Non-Numeric value passed as Withdraw Amount");
try {
ESAPI.httpUtilities().sendForward(request, response, "/error" );
} catch (AccessControlException ignored) { }
}

// Calling Withdraw will queue a check to be printed and mailed to the customer.
AccountFacade.withdraw( acct, amt );

try
{
ESAPI.httpUtilities().sendForward(request, response, "/success" );
}
catch (AccessControlException ignored) { }

return;
}
}


Now there are a couple things that I will point out that I am sure you will notice if you are paying attention. The first is that yes, this example is using the ESAPI. Call it a shameless plug :). The second is that I am ignoring AccessControlExceptions. This is purely to keep this example scenario short and to the point, and in any production code, you would never want to do this. There would also be some validation code in there as well.

Aside from those things, it looks innocent enough right? Well let's consider this for a second with a scenario.

Joe needs to have a check cut to him from his account at SomeBodiesBank. So he gets online and hits the form for the above servlet. Joe is not that savvy of a computer user, and like most novice internet users will do, he has the tendency to double-click on everything. He fills out the form to withdraw $500 from his account and double-clicks the submit button. So somewhere on the backend, we'll say in the AccountFacade.withdraw method, the software validates that Joe has enough money to cover the check, it discovers he has $750 in his Checking account so everything looks good. But wait a minute, Joe double-clicked remember?

Do you know what happens when you double click the submit button on a form? Well, 2 requests get submitted one after the other. Hmmmmmm.. So now I have 2 requests entering this method at the exact same time, both requests check Joe's balance and discover that he has $750 in his account, so they both queue up a request to print a check for the requested amount. There's only one problem, these are cashiers checks, the bank has withdrawn $1000 dollars (or in some circumstances, maybe only withdrew the original $500 from his account) but Joe ended up with $1000 in cashiers checks!

The checks show up in the mail, and Joe being the responsible individual he is, reports this to the bank. The bank will likely write this off as an anomoly and the bug will remain until one day when Joe is down on his luck and remembers the bug. He finds a program called JMeter and submits 1000 requests to the servlet as fast as he can for $1000 withdrawals. When his 1,000,000 in cashiers checks arrive, he promptly leaves the country and disappears in the backwoods of New Zealand never to be heard from again.

So the moral of the story is that this problem could have been easily avoided simply by adding thread-safety measures to the code. Granted the example cited is extreme and the consequence of the example even more extreme, but I can promise you that something similar to the situation has already happened and even moreso I can guarantee that something similar will happen again.

So, with this knowledge, what is the correct means to add thread safety around manipulating the session. It's quite simple even.


final Object lock = request.getSession().getId().intern();
synchronized(lock) {
AccountFacade.withdraw( acct, amt );
}


Would do the trick in this simple example.

It's important when using synchronization to always lock on immutable objects. It is also important to use the same lock when locking in multiple places where you are working with the same data. Thread-safety is an entire subject on it's own that is will beyond the scope of this blog posting, so I will cut to the chase here.

This is incorrect, and not guaranteed:

synchronized (request.getSession()) {
// do stuff
}


While this method is proven and works:

synchronized (request.getSession().getId().intern()) {
// do stuff
}


Some interesting stats to close out with:

Google Code Search Results found approximately 4000 uses of different ways to say 'synchronized(session)'

The scary part is this was only the first 5 ways I came up with to search for it.

106 comments:

  1. Nice article. I think as we focus on application security issues the area of concurrency often gets over looked. Many time because it’s hard to spot as you rightly said.

    The more developers know of these issues during the creation process, the more they can proactively address the issues before the code is out the door.

    -Michael

    ReplyDelete
  2. Thanks! This concept of viewing application development from the viewpoint of application security is something that I think is important to start pushing. There are plenty of little things that can be ingrained into the developers mind (me being one of them) that will keep your applications more secure at the low-level and will make the job of the appsec guy better by allowing him to focus on appsec issues directly rather than appsec issues caused by incorrect coding practices.

    ReplyDelete
  3. Fantastic, it so great to come across a solution provided by someone who actually knows what he talks about - many thanks!

    ReplyDelete
  4. Of course for this example you would want some kind of database with optimistic / pessimistic row level locking, right?

    ReplyDelete
  5. Most modern relational databases come with some type of row locking mechanism out of the box to ensure that a read will wait for a concurrent write and visa versa (depending on the locking paradigm) so the short answer to your question is yes. However, it is important to note here that this isn't just an issue of concurrency, but also access control - it is also important to integrate access control decisions into data calls where you are dealing with sensitive data that may be subject to concurrency issues. Adding logic to ensure that a user can only modify data that he has access to and even adding timing thresholds (User A can modify this data once per minute) can go a long way in addressing threats that depend on concurrency issues.

    ReplyDelete
  6. interning can lead to a lot of permgen bloat can't it?

    ReplyDelete
  7. I have never heard of this happening and I have been doing this in some pretty heavy traffic applications for a while now. Definately worth checking into tho - I'll shoot off an e-mail to a couple colegues and see what they think. Since Strings are flyweight factoried, I wouuld think this would be a non-issue tho.

    ReplyDelete
  8. The problem with using the intern'd session ID is that the set of intern'd strings will slowly grow over the lifetime of the application. Since these session IDs will not be valid after the session itself has expired, this is a form of memory leak. After all, you cannot un-intern a string. If you have an app that deals with hundreds of thousands of sessions a day, this technique will not scale, and may quickly get you into trouble.

    Does anyone have experience implementing this technique on such a system?

    ReplyDelete
    Replies
    1. Interned Strings are garbage collected as long as there are no references to them.
      See Myth(buster) #3:
      http://www.codeinstructions.com/2009/01/busting-javalangstringintern-myths.html

      Delete
  9. getSession().getId().intern() ... pretty brilliant. Thanks!

    ReplyDelete
  10. Just stumbled across your blog and was instantly amazed with all the useful information that is on it. Great post, just what i was looking for and i am looking forward to reading your other posts soon!
    Data Science course in kalyan nagar
    Data Science course in OMR
    Data Science course in chennai
    Data science course in velachery
    Data science course in jaya nagar
    Data Science interview questions and answers

    ReplyDelete
  11. Nice post. By reading your blog, i get inspired and this provides some useful information. Thank you for posting this exclusive post for our vision. 
    Best Devops Training in pune
    Devops Training in Bangalore
    Microsoft azure training in Bangalore
    Power bi training in Chennai

    ReplyDelete
  12. Thanks For Sharing The InFormation The Information Shared Is Very Valuable Please Keeep updating Us Time Just Went On reading the article Python Online Course Data Science Online Course Data Science Online Course Hadoop Online Course Awsw Online Course



    ReplyDelete
  13. great information.
    thank you for posting.
    keep sharing.

    ReplyDelete
  14. Attend The Best Python Training in Bangalore From ExcelR. Practical Python Training in Bangalore Sessions With Assured Placement Support From Experienced Faculty. ExcelR Offers The Best Python Training in Bangalore.

    ReplyDelete
  15. Awesome post sir,
    really appreciate for your writing. This blog is very much useful...
    Visit Us- Digital Marketing Course

    ReplyDelete
  16. Attend The Data Analytics Courses in Bangalore From ExcelR. Practical Data Analytics Courses in Bangalore Sessions With Assured Placement Support From Experienced Faculty. ExcelR Offers The Data Analytics Courses in Bangalore.
    ExcelR Data Analytics Courses in Bangalore

    ReplyDelete
  17. This is a wonderful post, Given so much info in it, These type of post keeps the users interest in the website, and keep on sharing more. good luck!!
    Artificial Intelligence Course

    ReplyDelete
  18. Congratulations This is the great things. Thanks to giving the time to share such a nice information.best Mulesoft training in bangalore

    ReplyDelete
  19. Excellent post for the people who really need information for this technology.ServiceNow training in bangalore

    ReplyDelete
  20. I love it when people get together and share ideas. Great blog, stick with it! onsite mobile repair bangalore Good information. Lucky me I discovered your blog by chance (stumbleupon). I have saved it for later! asus display repair bangalore This website was... how do you say it? Relevant!! Finally I've found something that helped me. Thank you! huawei display repair bangalore

    ReplyDelete
  21. I was very pleased to uncover this great site. I wanted to thank you for your time for this particularly fantastic read!! I definitely really liked every bit of it and I have you book-marked to check out new things in your website. online laptop repair center bangalore Can I simply say what a comfort to discover a person that really understands what they are talking about over the internet. You certainly realize how to bring a problem to light and make it important. A lot more people ought to look at this and understand this side of your story. I was surprised you aren't more popular since you surely have the gift. dell repair center bangalore

    ReplyDelete
  22. Good post. I certainly appreciate this website. Stick with it! macbook repair center bangalore It’s difficult to find well-informed people about this topic, but you seem like you know what you’re talking about! Thanks acer repair center bangalore

    ReplyDelete
  23. Thanks for sharing it.I got Very valuable information from your blog.your post is really very Informatve.DevOps Course in Pune at 3RI Technologies. I’m satisfied with the information that you provide.

    ReplyDelete
  24. you are posting a good information for people and keep maintain and give more update too.
    Thanks and Regards : best python training in pune | python course in pune | 3ritechnologies technologies

    ReplyDelete
  25. Thanks for sharing it.I got Very valuable information from your blog.your post is really very Informative.I’m satisfied with the information that you provide for me.Software testing is a process ensure that the product is defect free.By reading your blog, i get inspired and this provides some useful information. Keep it up and best of luck for your future blogs posts.

    software testing institute in pune at 3ri Technologies

    ReplyDelete
  26. Your article is really amazing to read this is my first visit and please share this type of article it also provides information. And I would like to thanks for this information that I had been looking.
    Devops Training Institute in Pune

    ReplyDelete
  27. This post is really nice and informative. The explanation given is really comprehensive and useful... data science tutorial

    ReplyDelete
  28. Hey, thanks for this great article I really like this post and I love your blog and also Check Marketing Analytics with phyton. In 360DIGITMG Marketing Analytics with python provides an overview of how Python and R programming can be employed in Data Mining of structured (RDBMS) and unstructured (Big Data) data. Comprehend the concepts of Data Preparation, Data Cleansing and Exploratory Data Analysis. Perform Text Mining to enable Customer Sentiment Analysis. Learn Machine learning and developing Machine Learning Algorithms for predictive modeling using Regression Analysis. Assimilate various black-box techniques like Neural Networks, SVM and present your findings with attractive Data Visualization techniques.
    360Digitmg Marketing Analytics with python

    ReplyDelete
  29. Amazing article sir. A great information given by you in this blog. It really informative and very helpful. Keep posting will be waiting for your next blog.Thank you.


    Devops training in Pune


    ReplyDelete
  30. Took me time to read all the comments, but I really enjoyed the article. It proved to be Very helpful to me and I am sure to all the commenters here! It’s always nice when you can not only be informed, but also entertained!
    360Digitmg financial analytics training in hyderabad

    ReplyDelete
  31. I found a lot of information here to create this actually best for all newbie here. Thank you for this information.
    Artificial Intelligence Training In Hyderabad

    Artificial Intelligence Course In Hyderabad

    ReplyDelete
  32. Hi, Thanks for sharing wonderful articles...

    For More:

    AI Training In Hyderabad

    ReplyDelete
  33. I really enjoyed your blog Thanks for sharing such an informative post.

    digital marketing course in hubli

    ReplyDelete

  34. Thanks for sharing an informative blog keep rocking bring more details.I like the helpful info you provide in your articles. I’ll bookmark your weblog and check again here regularly. I am quite sure I will learn much new stuff right here! Good luck for the next! devops training in chennai | devops training in anna nagar | devops training in omr | devops training in porur | devops training in tambaram | devops training in velachery

    ReplyDelete
  35. Thanks for sharing an informative blog keep rocking bring more details.I like the helpful info you provide in your articles. I’ll bookmark your weblog and check again here regularly. I am quite sure I will learn much new stuff right here! Good luck for the next!Java training in Chennai

    Java Online training in Chennai

    Java Course in Chennai

    Best JAVA Training Institutes in Chennai

    Java training in Bangalore

    Java training in Hyderabad

    Java Training in Coimbatore

    Java Training

    Java Online Training

    ReplyDelete
  36. Nice post. Thanks for sharing! I want people to know just how good this information is in your article. It’s interesting content and Great work.Very useful and informative content has been shared out here, Thanks for sharing it

    Azure Training in Chennai

    Azure Training in Bangalore

    Azure Training in Hyderabad

    Azure Training in Pune

    Azure Training | microsoft azure certification | Azure Online Training Course

    Azure Online Training


    ReplyDelete
  37. Excellent Blog! I would like to thank for the efforts you have made in writing this post. I am hoping the same best work from you in the future as well. I wanted to thank you for this websites!
    sap training in chennai

    sap training in velachery

    azure training in chennai

    azure training in velachery

    cyber security course in chennai

    cyber security course in velachery

    ethical hacking course in chennai

    ethical hacking course in velachery

    ReplyDelete
  38. Amazing post found to be very impressive while going through this post. Thanks for sharing and keep posting such an informative content.

    360DigiTMG Cloud Computing Course

    ReplyDelete
  39. Amazing article. Your blog helped me to improve myself in many ways thanks for sharing this kind of wonderful informative blogs in live.
    acte reviews

    acte velachery reviews

    acte tambaram reviews

    acte anna nagar reviews

    acte porur reviews

    acte omr reviews

    acte chennai reviews

    acte student reviews

    ReplyDelete
  40. You finished certain solid focuses there. I did a pursuit regarding the matter and discovered almost all people will concur with your blog.
    data science course in noida

    ReplyDelete
  41. This is really very nice post you shared, i like the post, thanks for sharing..
    Data Science Training

    ReplyDelete
  42. Visit here to know more about AWS Training in Chennai . Cognex is the best institute in chennai to teah AWS

    ReplyDelete
  43. I pay a visit every day a few blogs and sites to read articles, but this weblog offers feature based writing.
    leather sofa set

    ReplyDelete
  44. I see some amazingly important and kept up to length of your strength searching for in your on the site
    Data Science Training in Hyderabad

    ReplyDelete
  45. I read this article fully on the topic of the resemblance of most recent and
    preceding technologies, it’s remarkable article.

    Study in Ireland Consultants

    ReplyDelete
  46. Fantastic blog! Thanks for sharing a very interesting post, I appreciate to blogger for an amazing post.
    Devops Training Institute in Pune
    Devops Training in Pune

    ReplyDelete
  47. Admiring the dedication you put into your blog and in depth information you provide.
    It’s awesome to come across a blog every once in a while that isn’t the same old rehashed information. Fantastic read! Software Security Solutions

    ReplyDelete
  48. Thanks for Sharing a Very Informative Post & I read Your Article & I must say that is very helpful post for us.
    Point cloud to 3D Model London
    Point cloud to 3D Model
    Reverse Engineering Services in London

    ReplyDelete
  49. Thanks for Sharing a Very Informative Post & I read Your Article & I must say that is very helpful post for us.
    Data Science Course in Pune
    Python Classes in Pune
    Best AWS Training in Pune
    Best RPA Training in Pune

    ReplyDelete
  50. keep sharing an informative content.
    https://www.3ritechnologies.com/course/devops-training-in-pune/

    ReplyDelete
  51. I loved reading this blog post. Very unique and Informative .I will definitely refer my friends to read this. Thanks for sharing with us.
    Best Web development company in Hyderabad

    ReplyDelete
  52. Thanks for your marvelous posting! I really enjoyed reading it, you could be a great author. I will be sure to bookmark your blog and definitely will come back in the foreseeable future. I want to encourage you to continue your great posts, have a nice afternoon! Best Digital Marketing Courses in Bangalore


    ReplyDelete
  53. A good blog always comes-up with new and exciting information and while reading I have feel that this blog is really have all those quality that qualify a blog to be a one.
    data scientist training in malaysia

    ReplyDelete
  54. This is really very nice post you shared, i like the post, thanks for sharing..
    data science training

    ReplyDelete
  55. Very nice job... Thanks for sharing this amazing and educative blog post!
    data science training in malaysia

    ReplyDelete
  56. Excellent post.I want to thank you for this informative read, I really appreciate sharing this great post.Keep up your work
    data science course in malaysia

    ReplyDelete
  57. Nice blog and absolutely outstanding. You can do something much better but I still say this perfect.Keep trying for the best.
    data analytics courses in hyderabad

    ReplyDelete
  58. After reading your post, thanks for taking the time to discuss this, I feel happy about it and I love learning more about this topic..Signova

    ReplyDelete
  59. A good blog always comes-up with new and exciting information and while reading I feel that this blog really has all those qualities that qualify a blog to be one.
    business analytics training in hyderabad

    ReplyDelete
  60. Гадание онлайн на самое ближайшее это шанс просмотреть будущие явления непрерывно привлекал человека. Ворожба дозволяет угадать, что человека ждет в предстоящем времени. Каждый желает подсмотреть свою судьбу и считает конкретные виды гадания гораздо больше эффективными.

    ReplyDelete
  61. this is such a satisfying aid that you are supplying and you pay for it away for pardon. ZookaWare Activation Code

    ReplyDelete
  62. yes i am fully decided on amid this text and that i simply indulgent pronounce that this article is deeply best and pretty informative article.i will make hermetically sealed to be studying your blog extra. SuperAntiSpyware Professional Keys

    ReplyDelete
  63. thanks for this usefull article, expecting this text related to this taking into account once more. Good Morning Masage

    ReplyDelete
  64. Get dual certification from IBM and UTM Malaysia with the 360DigiTMG Data Science Certification program.
    Data Science in Bangalore

    ReplyDelete
  65. We are manufacturing world's best lifts for homes in India. We are providing the certified lifts for your homes, buildings, bungalows and villas. A leading Home Lifts Company take us to the next level with understanding of home Lifts & Elevators.There are many Home lifts companies are there. Nibav Lifts is one of the best small lifts for homes in India.

    ReplyDelete
  66. Nice Post,
    Advantages of DevOps
    Improved Delivery
    The entire team is accountable for providing new features as well as maintaining the stability of existing software. This aids in exposing the problem at an earlier stage of development. Because the development team does not have to wait for other teams to troubleshoot and test, resolution times are shorter. By concentrating on business needs first, projects are completed first, which aids in the transition to a production environment. DevOps technique aids in responding to market demands more quickly. Devops course in Pune

    ReplyDelete
  67. Hello Sir I saw your blog, It was very nice blog, and your blog content is awesome. digital marketing

    ReplyDelete
  68. You explained the topic very well. The content has provided meaningful information thanks for sharing. intresting to gain knowledge then checkout our blog full stack course in pune

    ReplyDelete
  69. The code you provided seems to be a servlet that handles a withdrawal request. In this example, synchronizing the session is important to ensure that the session data is accessed and modified in a thread-safe manner.

    Here are a few reasons why you might want to synchronize access to the session:

    Concurrency: If multiple requests are being processed simultaneously, there is a possibility of race conditions where different threads try to access or modify the session concurrently. Synchronizing the session ensures that only one thread can access the session at a time, preventing data corruption or inconsistent behavior.

    Consistency: Synchronizing the session guarantees that the session attributes accessed or modified by different parts of the code remain consistent. In your example, you retrieve the "acct_" attribute from the session, and it's important to ensure that no other thread modifies or removes this attribute while you are working with it.

    Thread-Safety: Some containers, like Tomcat, may return a facade object that wraps around the actual HttpSession object. These facade objects may have their own internal synchronization mechanisms. By synchronizing access to the session, you ensure that you're working with the actual session object and not just its facade.

    To synchronize access to the session, you can use the synchronized keyword on the session object itself or use explicit synchronization blocks to control access to critical sections of code that interact with the session.

    Here's an example of using explicit synchronization blocks in your code:
    java

    public class WithdrawFundsServlet extends HttpServlet {

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException {
    User u = ESAPI.authenticator().getCurrentUser();
    String withdrawAmt = request.getParameter("withdrawAmt");
    float amt;
    Account acct;
    synchronized (request.getSession()) {
    acct = (Account) session.getAttribute("acct_" + u.getAccount());
    }

    // Rest of your code...
    }
    }

    By synchronizing the block of code where you access the session attribute, you ensure that only one thread can access the session at a time, avoiding potential issues caused by concurrent access.

    Remember to synchronize only the necessary sections of code to minimize the impact on performance and avoid potential deadlock situations.
    Jobs Listings
    Visit Serafelagi.com!
    I hope this clarifies the importance of synchronizing the session in your code. Let me know if you have any further questions!

    ReplyDelete
  70. You're absolutely right that using UUIDs as database record identifiers can have several benefits, such as uniqueness, compatibility across different systems, and reduced risk of collisions. However, you've correctly pointed out that there can be challenges when working with UUIDs in the context of JDBC and SQL.

    While UUIDs are not recognized as a standard data type in SQL or JDBC, there are ways to handle them effectively. Here are a few approaches you can consider:

    Storing UUIDs as String or Binary: Since UUIDs are typically represented as strings (e.g., "550e8400-e29b-41d4-a716-446655440000") or binary data, you can store them as such in your database. In the case of Postgres, you can use the uuid data type or store the UUID as a string or binary data in a column.

    Converting UUIDs in SQL: If you're working with databases that don't have native UUID support, you can store UUIDs as strings or binary data in a column and handle conversions in your SQL queries. For example, you can use functions like UUID_TO_BIN or BIN_TO_UUID to convert between binary and string representations of UUIDs.

    Custom Mapping in JDBC: JDBC provides mechanisms to handle non-standard data types through custom mappings. You can create a custom mapping between the UUID class in Java and the appropriate data type in your database. This allows you to work with UUIDs seamlessly in your Java code while transparently converting them to the corresponding database representation.

    Here's an example of registering a custom mapping for UUIDs in JDBC:
    java

    // Assuming you have a connection object named 'connection'
    java.util.Map> typeMap = connection.getTypeMap();
    typeMap.put("uuid", java.util.UUID.class);
    connection.setTypeMap(typeMap);

    By registering the custom mapping, you can retrieve UUID values from the database using the java.util.UUID class.

    It's worth noting that the specific approach you choose may depend on the database system you're using, as different databases have varying degrees of support for UUIDs.
    Jobs Listings
    Visit Serafelagi.com!
    While working with UUIDs in the JDBC and SQL ecosystem may involve some additional considerations and conversions, it's certainly possible to utilize UUIDs effectively in your database design. The benefits they provide, such as uniqueness and compatibility, often outweigh the challenges involved in handling them across different layers of your application.

    ReplyDelete

  71. law assignment help services in Canada play a pivotal role in enriching student life by providing essential support in navigating complex legal concepts. These services contribute to better education outcomes, fostering a deeper understanding of the law and preparing students for successful careers in the legal field.

    ReplyDelete
  72. Very Nice Blogs Keep up the excellent work!" Visit to AWS Training in Pune

    ReplyDelete
  73. I appreciate your kind words about the content. It's always a pleasure to know that you find the information valuable and the ideas presented enjoyable. I'll continue to strive for excellence in my work. Thank you for your encouragement!

    Visit : Automated vs. Manual Software Testing: Pros and Cons

    ReplyDelete
  74. Thank you for sharing. I consistently find delight in engaging with such outstanding content, filled with valuable insights. The presented ideas are truly excellent and captivating, adding to the overall enjoyment of the post.
    visit: Java Unveiled: From Basics to Brilliance

    ReplyDelete
  75. thanks for sharing valuable information on Synchronizing the HttpSession, also wanted to learn about Full stack Development then visit: Full Stack Java Course in Pune

    ReplyDelete