Nagappa L M
Nagappa L M

Reputation: 1480

A Servlets threads acces control

Friends inside a servlet method which is called by either dopost/doget i hava a code as

synchronized (this) 
{
String filePath="E:\\FSPATH1\\2KL06CS048\\";
System.out.println("Directory Created   ????????????"+new File(filePath).mkdir());
}

So more than one thread for the above servlet can enter the above block of code at once or not??

But Servlet LifeCycle Concept says there is only one instanse of Servlet and for each request of that servlet one thread is created on that instance.

Actually my requirement is

  1. make request(servlet call and job of this servlet is creating a directory in server)
  2. Once return from the servlet call i am renaming the created directory.
  3. While renaming,another thread must no create the same directory and modify the contents of directory because of this i want to synchronize sort of code in servlet

Upvotes: 0

Views: 158

Answers (3)

Nandkumar Tekale
Nandkumar Tekale

Reputation: 16158

Q. inside a servlet method which is called by either dopost/doget i hava a code as : synchronized (this) {}

---> Servlet Container(tomcat) will create a thread per request, so each time what you will have in your doGet() and doPost() method, will be local to respective threads. So you do not again need to synchronize this. So Your Idea is completely wrong.

Upvotes: 1

Ramesh PVK
Ramesh PVK

Reputation: 15446

Yes, your code will ensure that only one thread can enter the block.

Upvotes: 0

Azodious
Azodious

Reputation: 13872

synchronized ensures that only one thread can execute the enclosed block at one time.

Some more points:

  1. The synchronized keyword may be applied to a method or statement block and provides protection for critical sections that should only be executed by one thread at a time.

  2. The synchronized keyword prevents a critical section of code from being executed by more than one thread at a time.

  3. When applied to a static method, the entire class is locked while the method is being executed by one thread at a time.

  4. When applied to an instance method, the instance is locked while being accessed by one thread at at time.

  5. When applied to an object or array, the object or array is locked while the associated code block is executed by one thread at at time.

See that every statement ends with one thread at a time.

Upvotes: 1

Related Questions