Help to find the potential source of the problem in the code, and if it is, please provide a solution?

public class MyServlet extends HttpServlet { protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { List<User> users = DataProvider.getUsers(); for (User user : users) { resp.getOutputStream().println(user.getLastName()); ... } } } public class DataProvider { private static List<User> users = new ArrayList<User>(); public static void addUser(User u) { users.add(u); } public static List<User> getUsers() { return users; } } 
  • non-thread - safe user list - Russtam
  • Tell me what a thread-safe list of users should look like? - Alexander Dermenzhi
  • There are many options. As an option - use CopyOnWriteArrayList instead of ArrayList. Another option is to add the synchronized keyword to the addUser and getUsers methods and return a copy of the list to getUsers. This is all for safe work with the list. If the users themselves change too, then they should be solved with them. - Russtam

1 answer 1

resp.getOutputStream() can give you back

Throws: IllegalStateException - if the getWriter method has been called

IOException - if an input or output exception occurred

therefore, they need to be processed. Also check on null

user.getLastName () cannot return null?