Forum Controls
Spotlight Features

The Rich Engineering Heritage Behind Dependency Injection

Andrew McVeigh takes us on a tour of the rich heritage behind dependency injection, what it represents, and tells us why its here to stay.

NetBeans 6: Matisse Updates

NetBeans 6 delivers great updates to the Matisse GUI builder. Spend a few minutes with Roman Strobl and get an expert briefing on what's new and what has changed.

Introduction to Groovy Part 3

In this, the third and final installation of Andres' Introduction to Groovy series, you learn about how Groovy handles variable numbers of arguments, named parameters, currying, and more about Groovy operators. Including, some new operators.

Easier Custom Components with Swing Fuse

Swing Fuse (actually just Fuse), is a framework designed to make it easier to create your own custom desktop components. In this article, Daniel Spiewak shows you how to get started and provides sample source code you can download.

Benchmark Analysis: Guice vs Spring

Willam Louth shows how he uses JXInsight Probes to investigate probable performance issues with code bases that he is not familiar with. He also highlights possible pitfalls in creating a benchmark, as well as in the analysis of results.
Replies: 8 - Pages: 1  
Threads: [ Previous | Next ]
  Click to reply to this thread Reply

Thread-safe webapps using Spring - By Steven Devijver

At 12:32 PM on Dec 21, 2004, Matthew Schmidt wrote:

In this article, Steven explains why every web application developer should be aware of thread-safety. He starts by explaining what that means and then goes into depth on how you can achive that using Spring .

Read on for the full article.
1 . At 11:00 PM on Dec 28, 2004, john d hume wrote:
  Click to reply to this thread Reply

Re: Thread-safe webapps using Spring - By Steven Devijver

On the whole this is an ok article, but I'm confused about how this example from the article is not thread-safe.
private Double pi = null;

public Double pi() {
if (pi == null) {
pi = new Double(22 / 7);
}

return pi;
}

Two threads both see pi while it's null, so they both assign a new Double to it. Certainly that's not what's intended, and various threads that all call the pi() method might end up with different instances of pi, but given that all that matters about pi is its value, i.e., one instance is as good as the next, how is this dangerous? Is there some instability in the assignment operation that makes this dangerous in a way that isn't obvious?
2 . At 7:50 PM on Dec 29, 2004, Steven Devijver wrote:
  Click to reply to this thread Reply

Re: Thread-safe webapps using Spring - By Steven Devijver

John,

The code in the example wants to return a singleton object but fails to do so. I agree this example fails to illustrate this intention. With another object type this technique could lead to trouble. I'm having difficulties to come up with an example that demonstrates this, I'll try to post an example later on.

The assignment operation in this example should not cause any trouble. When two threads each create a Double instance in memory their next operation would be to assign the memory address of their instance to pi. An assignment operation is supposed to be atomic, meaning the virtual machine or operation system makes sure the assignment happens without interruption.

Thanks for your feedback

Steven
3 . At 3:03 PM on Jan 4, 2005, Clifton Craig wrote:
  Click to reply to this thread Reply

Re: Thread-safe webapps using Spring - By Steven Devijver

There were some good articles on the web that describe the anti-pattern called double check locking. Do a google search to find them as they describe the dangers of thread safety in detail. Basically the danger here comes from the possibility that the assignment could happen more than once. Since the assignment involves multiple steps, (creating an object then storing a reference to it) evaluating it multiple times could lead to more than one object created with only the last one being valid. Consider the follwoing chain of events:

Thread 1: pi == null == true
Thread 2: pi == null == true
Thread 2: Create Double at address 1
Thread 2: Store address 1 in pi
Thread 2: return address 1 to caller
Thread 1: Create Double at address 2
Thread 1: Store address 2 in pi
//address 1 is now invalid and a candidate for garbage collection
Thread 1: return address 2 to caller

Somewhere in thread 2 an invalid reference to address 1 lives and may be acted upon. I don't know the low level details of the JVM but it sounds possible that this behaviour can cause serious problems. More importantly a far more serious problem exists with this design. The problem is the possibility of a reference to an uninitialized object being acted on. You see with the singleton pattern you MUST syncronize the construction or move it out of the multi-thread domain. Suppose for example, the Double object had some initialization code of it's own. (which may or may not be the case.) Well if you allow multiple threads in the factory method then one could update the private instance with a reference before the constructor finishes. Other threads could then see the reference as not null upon entering the factory method and start using it while the contructor is still running in the constructing thread. It's just not a safe situation no matter how simple your objects are.
If you don't know, now you know.
4 . At 2:54 AM on Jan 7, 2005, John Olsson wrote:
  Click to reply to this thread Reply

Re: Thread-safe webapps using Spring - By Steven Devijver

The second example (which Steven claims to be thread safe), is actually not thread safe at all! It looks like this

private static ThreadLocal pi = new ThreadLocal();

public Double pi() {
if (pi.get() == null) {
pi.set(new Double(22 / 7));
}

return (Double)pi.get();
}

since it still uses the "double check locking" anti pattern (please look at Clifton Craigs post for more details). The simple story is that to competing threads can both execute to the point that they have both checked if pi.get() returns null, and thus both threads could execute pi.set()!

In order to get this example thread safe you still have to use manual synchronization like this

private static ThreadLocal pi = new ThreadLocal();

public synchronized Double pi() {
if (pi.get() == null) {
pi.set(new Double(22 / 7));
}

return (Double)pi.get();
}

One other thing to keep in mind regarding synchronization is that each thread in Java is allowed to cache data. The only way to force a flush of this cache to the heap is to enter/exit a synchronized region!
5 . At 5:37 AM on Jan 7, 2005, Steven Devijver wrote:
  Click to reply to this thread Reply

Re: Thread-safe webapps using Spring - By Steven Devijver

Calling ThreadLocal.set(Object) concurrently is thread-safe. The set method ties data to the current thread. Take a look at the code to judge for yourself:

http://pistos.pe.kr/javadocs/j2sdk-1_4_x/j2h/java/lang/ThreadLocal.java.html

On your point about flushing data to the heap through synchronization I could not find any reference. Could you please ellaborate?
6 . At 9:06 AM on Jan 7, 2005, Clifton Craig wrote:
  Click to reply to this thread Reply

Re: Thread-safe webapps using Spring - By Steven Devijver

Steven,

I appreciate your referencing my post. However the example does not use double check locking and it does appear to be thread safe. The double check locking anti-pattern attempts to work around the threading issue with global or member variables by aquiring a lock. It also attempts to work around potential congestion by aquiring a lock right around the code that needs it. In practice it looks like this:
class MyFactory
{
   static MyClass myVar;
 
   public static MyClass myClassFactory()
   {
      if(null==myVar)
      {
         synchronized(MyFactory.class)
         {
            if(null==myVar) myVar = new MyClass();
         }
      }
      return myVar;
   }
}

The key is the second check for null which unsuccessfully tries to address the congestion and locking problems. The example however, never checks any static or member variables. Instead it checks a member of a member variable which is assigned to the particular thread. The pi variable is initialized on class loading so it should never be a thread issue. The null check referrs to a specific instance maintained for the current thread. I've never used ThreadLocal before but in principal I can imagine its job is quite simple. It most likely maintains a Map of instaces for each thread while delegating the get method to the Map and passing the current thread as a key.
public class ThreadLocal
{
   Map instances;
   public ThreadLocal()
   {
      instance = new HashMap();
   }
 
   public void initialValue() {return null;}
 
   public void set(Object value)
   {
      instances.put(Thread.currentThread(), value);
   }
 
   public Object get()
   {
      Object result = instances.get(Thread.currentThread());
 
      if(null==result) return initialValue();
      else return result;
   }
}


See? Since the value on the get/set is associated with the calling thread there is no conflict between multiple threads setting or getting the same value. I brought up the double check locking anti-pattern to explain why the initial example could be problematic not too confuse things. One thing I am interested in is your mentioning the need to flush the thread local cache. I don't quite follow.

Kind Regards,
Cliff
If you don't know, now you know.
7 . At 3:15 PM on Mar 10, 2005, Rodolfo de Paula wrote:
  Click to reply to this thread Reply

Re: Thread-safe webapps using Spring - By Steven Devijver

> One other thing to keep in mind regarding
> synchronization is that each thread in Java is
> allowed to cache data. The only way to force a
> flush of this cache to the heap is to enter/exit a
> synchronized region!


So, for example:

A thread is processing a http request. It invoke a servlet method, which is thread safe. This servlet instantiate a ThreadLocalCustomerDAO for reuse only within this thread (request, anyway). After processing this request, the current thread still has its ThreadLocalCustomerDAO state and thereafter the next http request will see this state, causing possible data corruption ?

This state will be only garbaged collected within a synchronized region ?

Or in other way, ThreadLocalized data persists within the thread even after the lifetime of the current http request ?

Thanks
8 . At 11:55 PM on Apr 19, 2008, Neal Neal wrote:
  Click to reply to this thread Reply

Re: Thread-safe webapps using Spring - By Steven Devijver

I am in a kind of bind.
I am looking at some existing code at a company.
They used a homegrown setup/framework which is a garbage version of Hibernate. They use no Spring. They use hbm.xmls. Using the existing setup is very painful and hence mentally decided to make my own AnnotationSessionFactory, hook it to Spring and go my merry way

But there is a booby-trap in setup
They use the HibernateSessionFilter you mentioned..a bibernate session is associated to a web request and ends when response comes back. I cannot switch off that filter as some portions of the app uses the old way of doing things...and there is just too much work to convert.
The existing filter opens the session and starts a transaction.

So question is, will my strategy work? There would be two SessionFactories(one mine and one theirs hooked to one jndi datasource, but with different mapping files).
Now what confounds me is which session would it use...My session is made from a SessionFactory which is made of mapping file A and the existing SessionFactory is made from mapping file B. Both use the Hibernate TransactionManger to manage a transaction, but demarcations are diff(mine at service layer and the existing at start of http request)

I have no way of killing the existing HibernateSessionFilter . So is my trying to use Spring and Hibernate in the application dead in the water?

thread.rss_message