Reputation: 1480
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
Upvotes: 0
Views: 158
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
Reputation: 15446
Yes, your code will ensure that only one thread can enter the block.
Upvotes: 0
Reputation: 13872
synchronized
ensures that only one thread can execute the enclosed block at one
time.
Some more points:
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.
The synchronized keyword prevents a critical section of code from being executed by more than one thread at a time.
When applied to a static method, the entire class is locked while the method is being executed by one thread at a time.
When applied to an instance method, the instance is locked while being accessed by one thread at at time.
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