简体   繁体   中英

singletons and threads

My question is about threads being queued. For my example I have one Spring context. I have a method named CalculateTax in a stateless class. A request comes in, a thread is created (tA) and it eventually enters the CalculateTax method. Within the same "time frame" another request comes in and another thread is created (tB). Now, here is what I want to understand. AFAIK tB cannot execute CalculateTax until tA has exited the method. Is this true?

As long as CalculateTax only uses local variables (ie declared in the method), you will not have any thread sync issues and multiple threads can call the method without a problem.

However if for some reason CalculateTax uses variables defined at the class level, and you are using the Singleton pattern (you tagged your question with "singleton", so I guess you are), you may have thread sync issues.

No it is not true if they are parallel thread, each thread is in its own stack of execution so it should be able to execute while tA is executing.

This is what Threads are for.

Generally speaking the answer is undefined. If your 'request' comes from remote client the answer depends on implementation details of the mechanism used for service exposing.

However, I'm not aware about remote communication frameworks that really make the proxy serializing the requests, ie that is assumed to be addressed by target service developer (eg its your task to provide thread-safety for the service implementation OR serialize all requests using explicit synchronization etc).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM