0

I have a servlet that gets data and then persists it. Here is a rough snippet:

@WebServlet("/ListenerServlet")
public class ListenerServlet extends HttpServlet {

    @Inject
    private PersistService service;

    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {

    String toPersist = getDataFromRequest();
    service.persist(toPersist);
}

My questions

  • Is it OK to inject the (requestScoped) service via CDI like that ?
  • Can I create my own (non static) method in the servlet and be thread safe ? Do I need the synchronized keyword ?

Own method:

private void doPersist(String toPersist) {
    service.persist(toPersist);
}
JavaHopper
  • 5,567
  • 1
  • 19
  • 27
Tim
  • 3,910
  • 8
  • 45
  • 80
  • This topic also discusses about thread safety in Servlets http://stackoverflow.com/questions/20768720/if-my-servlet-instance-variable-is-of-type-stringbuffer-is-it-thread-safe – JavaHopper Jul 28 '16 at 15:09

1 Answers1

0

Having your own methods is absolutely fine - as long as they too are thread safe. Injecting your PersistService is a great way to get your backing store into the servlet but it's still important that the PersistService is thread safe too. For example, if you've got a static EntityManager in that class then that is not thread safe without some additional synchronization. But if you're doing your persistence in a thread safe way then you should be fine.

In general the pattern you're using is one that I've used many times and it works well.

You may refer to these questions:

Regarding thread safety of servlet

Why Servlets are not thread Safe?

If my Servlet instance variable is of type StringBuffer, is it thread-safe?

Community
  • 1
  • 1
stdunbar
  • 16,263
  • 11
  • 31
  • 53