Question

I am giving users the option to edit the files in my db. But i dont want multiple edits to the same file at the same time and therefore to prevent this i have used a static linked list on my server side. When the client will send the request to update file to server , LinkedList.contain(filename) will check if the file name exists in the list or not. If it doesn't exist then it will add it and allow update, else it will just return the response as an error occurred.. The code is something like this:

public class UpdateFileServlet extends HttpServlet{

    private static List<String> List= new LinkedList<String>();
        @Override
        public void doPost(HttpServletRequest req, HttpServletResponse res)
                    throws ServletException, IOException {
            String file=req.getHeader("FileName");
            if(List.contains(file)){
                res.getWriter().write("Error");
                res.flushBuffer();
                return;
            }
            List.add(file);
            try{
            //do the file update;

                List.remove(file);

            }catch (Exception e1) {
                List.remove(file);
                e1.printStackTrace();
            }
        }
    }
}

I have also added try/catch, so that even if any exception occurs then also the name of the file will be removed from the list. Otherwise the file will become non editable forever. I know this isn't the best method, but i want to know if there is any condition in which the linkedlist will fail Or is there any better solution to the problem???

Thanks in advance for any help or suggestion...

Was it helpful?

Solution

Several points.

  1. LinkedList isn't thread safe. Also searching time is linear. You might want to consider ConcurrentHashMap. Instead of doing list.add() you do ConcurrentMap.putIfAbsent() and check the returned value.

  2. People might pass in different path e.g. absolute vs relative path all pointing to the same actual file. So it's better to use File object instead of string in your holding structure.

  3. I guess you want to do list.remove(file) regardless if the update is successful. So you need to put it to the finally block.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top