Issue
I'm writing a servlet program to access the files to write, based on the request made by the client. The request contains the file name. Let's say 3 requests are made at the same time. If two of them requests for the same file, then the file has to be accessed in the synchronized manner ie.., only after completed serving any one request, the next one can be served. If the third request which is also made in the same time, requests for a different file name, it has to be served concurrently along with the other request. How to handle this case of both synchronized and concurrent access to the files?
I have tried using a synchronized block on for the file access. But this does not allow concurrent access for requests with different file names.
public class FileServlet extends HttpServlet{
String FileName="";
public void service(HttpServletRequest req, HttpServletResponse res) throws IOException
{
FileName = req.getParameter("file");
synchronized(FileName){
//writing on fileName
}
}
}
Here, all the files requested are accessed in a synchronized manner. But i expect to access different files in a concurrent manner.
Solution
Create class which implements Thread
class or extends Runnable
interface for file access. Then, create multiple threads using that class and call join()
on each thread to do all the tasks concurrently.
Or you can use :
Map<Type, Type> map = new ConcurrentHashMap<Type, Type>();
// which is thread-safe to access resources.
Answered By - Anish B.