Reputation: 8800
I am confused if we should make our own threads in servlet or not,as they have threading mechanism internally?. If yes how can we make sure if the program thread safe? How to implement thread safe mechanism in servlets.
Upvotes: 2
Views: 1057
Reputation: 299218
You are asking two different questions:
I am confused if we should make our own threads in servlet or not,as they have threading mechanism internally?.
Normally, you should not start threads in a Java EE application. If you need seperate threads, make sure you use a Scheduler Service that your application knows about, so that it has the chance to shut down the threads when the application is shut down. Quartz is what's used most of the time.
If yes how can we make sure if the program thread safe? How to implement thread safe mechanism in servlets.
Servlets are just like any other Java class. Find a tutorial on thread safety or read Java Concurrency in Practice.
Upvotes: 2
Reputation: 3321
From what you write in the comment, I understand that you have a set of threads continuusly monitoring log-files and sending email if something interresting is found in the log.
First question: why is this a servlet? Is there a web-gui? What is this used for?
For the log-scanning part, I would have implemented that as a separate process outside of the servlet-container. For everything this process found which it needs to send somewhere, I would add a message to a JMS-queue. Then I would create a messagedriven bean to recieve messages from this queue and send them as email. (This is really an integration problem, transforming messages from JMS to email, you might want to look into something like Mule to solve this).
As for how to integrate this with your servlet, it depends on what your servlet does in addition to scanning logs (I suppose it presents the user with some kind of interface)
With this design, you can chose to re-write the programs generating the log in the future. Instead of having one program writing log and another program parsing the log, the first program might as well put the interresting message directly on the JMS-queue. In other words, you can change the log-generation part of your architecture in the future, without having to re-write the mail-sending part.
Upvotes: 1
Reputation: 54094
I also had a similar concern.
Only EJB
specification disallows the creation of threads from the application.
It is ok to start a thread from a servlet.
I have done it many times with no problems but to be honest I am not 100% sure:
or
But in Tomcat I never had an issue starting threads from a servlet.
You can make it thread safe the same way you do in every multithreading program.
You will use all the available constructs offered by Java for synchronization.
Upvotes: 1