I have general understanding that what thread safety means , but I don't know much about threads in context of a java webapplication. I am just curious to know that do I need to concern about thread safety while working with web application.Can their be chances that my web application will cause some problems if I have written codes without concerning about Thread safety? Do I need to think about that whether I am using a thread safe collection or not?
Do I need to care about 'Thread safety' in java web applications
java;jee
Yes you certainly do :) Most (all?) JEE web containers will run your classes with concurrent multiple threads. Also, frameworks like Spring MVC use singleton class instances to service all threads. But following a few simple guidelines will keep your code thread-safe.You cannot store data that belongs to the user in member variables of singleton classes (typically controllers and validators). User data belongs in the model, which must be user specific.You don't need to worry about thread-safe collections etc unless multiple threads are going to access them. This is unusual in a web application. For instance something like a whos logged in collection will need to be thread safe, but a list of values personal to the user need not be.Local variables declared inside methods don't need to be thread-safe, as each method invocation is automatically allocated a new variable.If your web framework provides a synchronise on session facility (Spring MVC does), I suggest you turn it on. This will mean that if the user hits submit twice in quick succession, the first submisstion will finish executing before the second starts. This gives you the chance to handle it intelligently. Without it there is a small but finite chance that two threads will fight over the user's data structure with odd results guaranteed.Access to global data structures must be designed with threading issues in mind. For instance a cache of values read from a database will definitely need to be thread-safe.Avoid using files for intermediate storage. Multi-threaded writes to a file are difficult to synchronise, and almost impossible if multiple JVMs are writing to the same file (as can happen in server farm or clustered installations). If you have this need, use a database - transaction control is far simpler.A special case arises when multiple users can update the same data. But this is not exactly a threading issue - try Google for long running transactions. It is a sizeable topic.So yes, you need to be thread aware, but in practice it is not a big problem.