Shared Variable Scopes and Locking

This is a post I made this morning on cf-talk in response to a thread on locking shared variable scopes. The short answer is that you don’t need to unless you are preventing a race condition. For the long answer, read on:

Just some additional interesting information on shared variable scopes: the reason you do not need to lock them (unless you are attempting to prevent a race condition) is that their underlying Java implementations use java.util.Hashtables. Hashtables are synchronized so that two threads cannot modify the same instance of a Hashtable concurrently. So Tony, you are right that Macromedia engineers did the right thing here, otherwise there would be a lot more cflocking going on. For instance, if they had used a HashMap, all access/modification would have to be locked (to prevent actual exceptions as opposed to just unexpected behavior), which would make for a lot more code with no advantages.

Another thing to note is that synchronization at such a low level is very fast and efficient; faster than using cflocks.