Showing posts with label concurrency. Show all posts
Showing posts with label concurrency. Show all posts

Tuesday, 8 April 2008

Java: synchronizing on an ID

If you are a Java programmer, you will be familiar with synchronized blocks.
  Object myObject = //some instance
  synchronized(myObject) {
   //do some thread-sensitive
   //work on myObject
  }
Sometimes, you want to synchronize on a transient object - a resource that isn't going to stay in memory.

For example, there is nothing in the Servlet 2.5 MR6 specification that says a HttpServletSession instance can't be recreated as a facade object every time it is requested. That makes the session instance a poor candidate for a synchronized lock. There is nothing in the specification that prevents the container implementer from always serializing session attributes as soon as they are set either. That makes session attributes poor candidates for synchronization locks. Note: existing implementations may support either of these approaches in practice, but lets say our imaginary servlet container doesn't. However, the session ID will be consistent across requests.