views:

514

answers:

4

In classic ASP there is a global object called "Application" that is accessed simultaniously by all sessions.

As the "Application" object is a shared resource, can it cause dead locks?

EDIT: If not, why does it has lock and unlock methods for? Reference

A: 

No, it never blocks.

Stefan Mai
A: 

A deadlock is a situation wherein two or more competing actions are waiting for the other to finish, and thus neither ever does.

MysticSlayer
+3  A: 

Deadlock is different from normal blocking. Since pages are processed in different threads, if you want to prevent another request from modifying that shared resource, you use Lock, and to allow modification again, you use the Unlock method. The thing is, if you don't use those methods, another request can change the value of an item in the application state, while you're relying on an old value. Or two requests can try to modify it simultaneously and it might cause problems. Lock method causes a request to wait until the other request unlocks application; after that, it can continue.

Deadlock is a situation in which thread A locks resource 1 and waits for resource 2 to become available. At the same time thread B, which has locked resource 2 needs to access resource 1 (which is locked by thread A) to continue to work and be able to release the resource afterwards. In this situation, none of the threads can continue (one of them has to be terminated to allow continuation). This is a deadlock. Application.Lock will not cause deadlocks on its own if correctly used. But if it's not used correctly, it might cause deadlocks (when coupled with another shared resource that needs locking and deadlocks are not taken care of).

Mehrdad Afshari
+2  A: 

It's unlikely that the locking the ASP Application object will result in a deadlock lasting longer than the server script timeout setting.

The classic ASP Application object has Lock and Unlock for synchronizing changes to the Application objects. You can have multiple requests trying to make a change to the same value - without locking, making the change and then unlocking the change might be lost.

As simple example would be a counter of some sorts. Let's say your code does:

<%
Application("Count") = Application("Count") + 1
%>

If you have two simultaneous requests (req1 and req2) , you could "lose" a page hit - effectively a "missing update".

You can prevent this by locking the Application variable before updating it and unlocking it after the update:

<%
Application.Lock
Application("Count") = Application("Count") + 1
Application.Unlock
%>

If Application is locked while another request thread tries to access it, the thread will block until the lock is released or the script timeout is exceeded.

If you forget to Unlock a Lock it will be released automatically after the page is processed or after the script timeout is exceeded.

For more information, see MSDN.

dariom