Joerg Heinicke wrote:

On 21.11.2005 13:17, Iacturus wrote:

As the NonThreadSafeComponent uses some API which cannot be made
threadsafe, there can only be one method of NonThreadSafeComponent
executed at one time. I cannot change this API and it really has to be
used exclusively.


Why don't you make your NonThreadSafeComponent thread safe? In the easiest case just add "synchronized" to each method. To assure that it is a singleton you have to implement ThreadSafe then.


Oooh, that's dangerous advice. There are two incredibly huge reasons why you shouldn't just blindly add "synchronized" to each method:

1. You pay an enormous price in synchronization overhead. As all the threads contend for the monitor, you are limiting only one client to have access to the component at a time. Sometimes it pays to have an instance per thread, or an instance per request to avoid monitor contention.

2. Blindly adding synchronized does not protect you from race conditions. Take for instance a Queue situation. One thread waits until the Queue says it has an item available polling the "size()" method--access is synchronized by the way. Another thread steals the instance before the first thread has a chance to pop the item off. The first thread's code dies because it assumed there would be something available.

I realize the last example was contrived, but it was to show that if you are relying on methods being called in a certain order you can't rely on that order in a multithreaded environment--even if the individual methods are synchronized.

The way around that is to use a token for the thread's "session" with the component. That token would hold whatever state is necessary for a particular thread's conversation with the component.

Point is, you have to plan for concurrent access, you can't just add the synchronized keyword to a method signature. You realize that by doing that the synchronization object is the whole object that the method belongs to? Typically there are only a couple objects that really need synchronization around them within the parent object, so you can minimize thread contention by only synchronizing on the parts that really need to be synchronized. That minimizes the time spent in monitor contention mode.


---------------------------------------------------------------------
To unsubscribe, e-mail: [EMAIL PROTECTED]
For additional commands, e-mail: [EMAIL PROTECTED]