I'm writing a servlet and I need to ensure it is thread safe.
How can I do that?
Thanks!
Printable View
I'm writing a servlet and I need to ensure it is thread safe.
How can I do that?
Thanks!
No generic way. Think about resources that one thread might access while another is modifying them. Make no assumptions about the order in which things happen. Then insert synchronization where necessary.
Yes CornedBee is right. There is really no generic way to write multithreaded code that trys to tap single resource. What you want to be careful of though is miss-synchronization or deadlock.
But, synchronization is not always the best possible soultion to the problem of inconsistent behavior as a result of thread scheduling. One technique used ensure thread safety is to use local variables instead of fields wherever possible since they do not have synchronization problems. Every time a method is entered the JVM creates a completely new set of local variables. The variables are destroyed when the method exits. This means that there is no possible way for a local variable to be used in teo different threads. Every thread has its own set of local variables.