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.

2 Responses to Shared Variable Scopes and Locking

  1. Jose says:

    Can you explain what you mean by “race condition” please?Also, are you saying that using cflock for shared scopes is really now a ‘thing of the past’ unless you have a specific condition in your code that requires it, and if so what conditions would those be in theory?(Very useful site by the way!)

  2. Christian says:

    It’s true that you do not have to worry about locking variables scopes because they are implemented as Java Hashtables, and Java Hashtables are thread-safe, which means it is impossible for two threads to access the same key/value pair simultaneously. A race condition refers to a circumstance where you need one event to happen before another event (as opposed to ensuring that both events don’t occur simultaneously), so you can use locking to ensure that the events occur in the proper order.Christian