Tuesday, February 24, 2015

Lock, ReentrantLock, ReentrantReadWriteLock and StampedLock in Java

The Lock implementations in Java are more flexible than using synchronized methods and statements. They support quite different properties and multiple Condition objects. The Lock interface has the following structure:

public interface Lock {
void lock();
void lockInterruptibly() throws InterruptedException;
boolean tryLock();
boolean tryLock(long time, TimeUnit unit) throws InterruptedException;
void unlock();
Condition newCondition();
}

When using any of the Lock implementation the lock is released in finally block. The general usage is:

Lock l = ...;
     l.lock();
     try {
         // access the resource protected by this lock
     } finally {
         l.unlock();
     }

The implementation classes for Lock provide additional functionality over synchronized methods and statements e.g. non-blocking or optimistic attempt to acquire a lock using tryLock(), attempt to acquire the lock that can be interrupted (lockInterruptibly()), and attempt to acquire a lock that can timeout (tryLock(long, TimeUnit)). A Lock class can also provide behavior quite different from implicit monitor lock, such as guaranteed ordering, non-reentrant usage, or deadlock detection.

Another interface related to locking is ReadWriteLock which has the following structure:
public interface ReadWriteLock {
    Lock readLock();
    Lock writeLock();
}

As per the Java Doc:
ReadWriteLock maintains a pair of associated locks, one for read-only operations and one for writing. The read lock may be held simultaneously by multiple reader threads, so long as there are no writers. The write lock is exclusive.
It provided more flexibility as it exploits the fact that only a single thread can modify whereas multiple threads can read at same time. The actual performance depends upon frequency of read-writes, duration of each operation, and the contention for the data i.e. no of threads that will try to read-write the data at same time.

New Request is for?Other thread is already readingOther thread is already writing
ReadGood to go.Stop and wait.
WriteStop and wait.Stop and wait.

The implementation classes for these interfaces are given below:
Lock: ReentrantLockReentrantReadWriteLock.ReadLock, ReentrantReadWriteLock.WriteLock
ReadWriteLock: ReentrantReadWriteLock




Although the basic operation of a read-write lock is straight-forward, there are many policy decisions that an implementation must make:
  • When both readers and writers are waiting whether to grant read or write lock?
  • Whether readers that request the read lock while a reader is active and a writer is waiting, are granted the read lock.
  • Whether the locks are reentrant: can a thread with the write lock reacquire it? Can it acquire a read lock while holding the write lock? Is the read lock itself reentrant?
  • Can the write lock be downgraded to a read lock without allowing an intervening writer? Can a read lock be upgraded to a write lock?
ReentrantLock
If a thread invokes lock() and does not own the lock then it will successfully acquire the lock and method will return.The method will return immediately if the current thread already owns the lock. This can be checked using methods isHeldByCurrentThread(), and getHoldCount(). In the following example we have two methods that will be invoked by two different threads, but each method will increment the count.

public class Incrementer {
    int count = 0;
    Lock lock = new ReentrantLock(); // Non-fair lock.

    public void incrementByFirstThread() {
        lock.lock();
        try {
            increment();
        } finally {
            lock.unlock();  // In any case lock must be released.
        }
    }

    public void incrementBySecondThread() {
        lock.lock();
        try{
            increment();
        } finally {
            lock.unlock();
        }
    }

    private void increment() {
        for(int i=0; i<1_000; i++) {
            count++;
        }
    }

    public void finished() {
        System.out.println("Finished with value: " + count);
    }
}

This is called by main method as shown below:
public static void main(String[] args) {
        Incrementer incrementer = new Incrementer();

        Thread thread1 = new Thread(() -> {
           incrementer.incrementByFirstThread();
        });

        Thread thread2 = new Thread(() -> {
            incrementer.incrementBySecondThread();
        });

        thread1.start(); thread2.start();
        try {
            thread1.join();
            thread2.join();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        incrementer.finished();
    }

Can you guess the output? If you have noticed there is one method in Lock interface newCondition() which returns a Condition object. Conditions provide a means for one thread to suspend execution until notified by another thread that some state condition may now be true. Lets take another example:

public class IncrementerWithCondition {
    int count = 0;
    Lock lock = new ReentrantLock(); // Non-fair lock.
    Condition condition = lock.newCondition();

    public void incrementByFirstThread() throws InterruptedException {
        lock.lock();
        System.out.println("Waiting for condition in incrementByFirstThread....");
        condition.await();

        try{
            increment();
        } finally {
            lock.unlock();
        }

        lock.unlock();
    }

    public void incrementBySecondThread() {
        lock.lock();
        System.out.println("Waiting for return key ....");

        Scanner scanner = new Scanner(System.in);
        scanner.nextLine();
        scanner.close();
        System.out.println("Hurray got return key notifying condition now..");
        condition.signal();

        try{
            increment();
        } finally {
            lock.unlock();
        }
    }

    private void increment() {
        for(int i=0; i<1_000; i++) {
            count++;
        }
    }

    public void finished() {
        System.out.println("Finished with value: " + count);
    }
}

Here in the method incrementBySecondThread lock is acquired and then it waits for the return key to be pressed. Once it is done it signals the condition and incrementByFirstThread resumes.

ReentrantReadWriteLock
The example for this will have Reader, Writer and a Dictionary class in which multiple readers can read but only one can write.

public class Reader extends Thread{
    private final Dictionary dictionary;
    private boolean keepRunning = true;

    public Reader(Dictionary dictionary, String name) {
        this.dictionary = dictionary;
        this.setName(name);
    }

    @Override
    public void run() {
        while (keepRunning) {
            String [] keys = dictionary.getKeys();
            for (String key : keys) {
                //reading from dictionary with READ LOCK
                String value = dictionary.get(key);

                //make what ever you want with the value.
                System.out.println(key + " : " + value);
            }

            //update every seconds
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }

    public void stopReader() {
        this.keepRunning = false;
        this.interrupt();
    }
}




The writer class is:
public class Writer extends Thread{
    private boolean keepRunning = true;
    private final Dictionary dictionary;

    public Writer(Dictionary dictionary, String threadName) {
        this.dictionary = dictionary;
        this.setName(threadName);
    }

    @Override
    public void run() {
        while (keepRunning){
            String[] keys = dictionary.getKeys();
            for(String key : keys) {
                String newValue = getNewValueFromBackEnd(key);
                dictionary.set(key,newValue);
            }

            //Update every 5 seconds
            try {
                Thread.sleep(5000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }

    public void stopWriter() {
        this.keepRunning = false;
        this.interrupt();
    }

    private String getNewValueFromBackEnd(String key) {
        return "NEW-VALUE";
    }
}

The Dictionary class is:
public class Dictionary {
    private final ReadWriteLock readWriteLock = new ReentrantReadWriteLock();
    private Map<String,String> dictionary = new HashMap<>();

    public void set(String key, String value) {
        readWriteLock.writeLock().lock();
        try {
            dictionary.put(key, value);
        } finally {
             readWriteLock.writeLock().unlock();
        }
    }

    public String get(String key) {
        readWriteLock.readLock().lock();
        try{
            return dictionary.get(key);
        } finally {
            readWriteLock.readLock().unlock();
        }
    }

    public String[] getKeys() {
        readWriteLock.readLock().lock();
        try {
            return (String[]) dictionary.keySet().toArray();
        } finally {
            readWriteLock.readLock().unlock();
        }
    }
    public static void main(String[] args) {
        Dictionary dictionary = new Dictionary();
        dictionary.set("java",  "object oriented");
        dictionary.set("linux", "rules");
        Writer writer  = new Writer(dictionary, "Writer");
        Reader reader1 = new Reader(dictionary ,"ReaderOne");
        Reader reader2 = new Reader(dictionary ,"ReaderTwo");
        Reader reader3 = new Reader(dictionary ,"ReaderThree");
        Reader reader4 = new Reader(dictionary ,"ReaderFour");
        writer.start();
        reader1.start();
        reader2.start();
        reader3.start();
        reader4.start();
    }
}

There was some problem with read-write lock in JDK 5 where multiple readers executing concurrently in critical section can lock all writer threads. In JDK 6 this problem was resolved but then readers seem to be starved. You can read more about this here.

StampedLock
Another related class is StampedLock which has three modes for controlling read/write access. The state of a StampedLock consists of a version and mode. Lock acquisition methods return a stamp that represents and controls access with respect to a lock state. The "try" versions may return the special value zero to represent failure to acquire access. The modes are:

  1. Writing. Method writeLock() possibly blocks waiting for exclusive access, returning a stamp that can be used in method unlockWrite(long) to release the lock. Untimed and timed versions of tryWriteLock are also provided. When the lock is held in write mode, no read locks may be obtained, and all optimistic read validations will fail.
  2. Reading. Method readLock() possibly blocks waiting for non-exclusive access, returning a stamp that can be used in method unlockRead(long) to release the lock. Untimed and timed versions of tryReadLock are also provided.
  3. Optimistic Reading. Method tryOptimisticRead() returns a non-zero stamp only if the lock is not currently held in write mode. Method validate(long) returns true if the lock has not been acquired in write mode since obtaining a given stamp. This mode can be thought of as an extremely weak version of a read-lock, that can be broken by a writer at any time. The use of optimistic mode for short read-only code segments often reduces contention and improves throughput. However, its use is inherently fragile. Optimistic read sections should only read fields and hold them in local variables for later use after validation. 
The following example demonstrates usage of StampedLock:
public class BankAccount {
    private final StampedLock stampedLock = new StampedLock();
    private int balance = 1000;

    public void deposit(int amount) {
        long stamp = stampedLock.writeLock();
        try {
            balance += amount;
        } finally {
            stampedLock.unlockWrite(stamp);
        }
    }

    public int getBalance() {
        long stamp = stampedLock.tryOptimisticRead();


        try {
            return balance;
        } finally {
            stampedLock.unlockRead(stamp);
        }
    }
}

The usage of optimistic locking using tryLock is slightly complicated. Consider this simplistic class of ComplexNumber:

public class ComplexNumber {
    private final double real;
    private final double imaginary;

    public ComplexNumber(double real, double imaginary) {
        this.real = real;
        this.imaginary = imaginary;
    }

    public double abs() { return Math.hypot(real,imaginary);}
    public double phase() { return Math.atan2(real, imaginary);} // between PI and -PI

    public ComplexNumber add(ComplexNumber c) {
        double real = this.real + c.getReal();
        double imaginary = this.imaginary - c.getImaginary();
        return new ComplexNumber(real,imaginary);
    }

    public double getReal() {
        return real;
    }

    public double getImaginary() {
        return imaginary;
    }
}



The method abs() needs to get hold of both real and imaginary parts to compute itself. We may need to lock it which we can do using optimistic locking as:

public double abs() {
        long stamp = stampedLock.tryOptimisticRead();   // No locking just optimistic read.
        double currentReal = real, currentImaginary = imaginary;
        if(!stampedLock.validate(stamp)) {
            stamp = stampedLock.readLock();
            try{
                currentReal = real; currentImaginary = imaginary;
            } finally {
                stampedLock.unlockRead(stamp);
            }
        }
        return Math.hypot(real,imaginary);
    }

In the above method after trying for optimistic read lock (using tryOptimisticRead) we need to validate the stamp to ensure everything is OK. If the stamp does not validate it means a write has acquired the lock in between and the values we have may be stale. So we again acquire the read lock but this time it is pessimistic and after getting it we assign the values and then compute the method.

This was a short introduction and I hope it was useful.

Monday, February 23, 2015

CountDownLatch in Java

CountDownLatch is a synchronizer that allows one or more threads to wait until a set of operations being performed in other threads completes. A CDL is initialized with a given count which specifies the number of parties involved. Whenever the method countDown() is called it decrements the value of count by one.

Generally a CDL is used when one or more threads are supposed to wait for a number of threads (parties) to finish. In that case waiting threads make use of await methods
which block until the count reaches zero, on other hand each party decrements the count whenever it finishes. When count is zero all waiting threads are released
and any subsequent invocations of await return immediately.



Unlike CyclicBarrier it is non-cyclic. If we need a version that resets the count then we should consider using a CyclicBarrier. A useful property of a CountDownLatch is that it doesn't require that threads calling countDown wait for the count to reach zero before proceeding, it simply prevents any thread from proceeding past an await until all threads could pass.

public class LatchBasicMain {

    static class Processor implements Runnable {
        CountDownLatch latch;

        public Processor(CountDownLatch latch) {
            this.latch = latch;
        }

        @Override
        public void run() {
            System.out.println("Started some work..");

            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }

            latch.countDown();
            System.out.println("Finished.");
        }
    }

    public static void main(String[] args) {
        int threadsCount = 5;
        CountDownLatch latch = new CountDownLatch(threadsCount);
        ExecutorService executorService = Executors.newFixedThreadPool(threadsCount);
        for(int i=0; i<threadsCount; i++) {
            executorService.submit(new Processor(latch));
        }

        // Main will wait for all other threads to finish.
        try {
            latch.await();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        System.out.println("Main Finished");
    }
}

I hope this post was informative.

Monday, March 17, 2014

Designing and developing Stock Ticker application in Flex (Part Three)

As we mentioned in part twowe need to optimize the code so as to remove Bindable meta data tag. The bindable code generates lot of bloat code. We can optimize this by removing the Bindable tag and using BindableUtils or ChangeWatcher.

We can bind only price property of the stock value object and can make the stock non-bindable.
public class NonBindableStock
{
 public var ticker:String;
 public var company:String;
 [Bindable] public var price:Number;  
 public function NonBindableStock(comp:String, tick:String, prc:Number)
 {
  this.price = prc;
  this.ticker = tick;
  this.company = comp;
 }
}
We can also make use of bindProperty method of BindingUtils and get hold of ChangeWatcher instance. We can remove the binding by calling unwatch() when we do not need it any more. This is straightforward and I am not giving any example for it.




Another optimization in the above case is to keep all the properties non-bindable and take care of notifying the view (datagrid) when data changes in our hand. In this case class will be same as:
public class NonBindableStock
{
 public var ticker:String;
 public var company:String;
 public var price:Number;  
 public function NonBindableStock(comp:String, tick:String, prc:Number)
 {
  this.price = prc;
  this.ticker = tick;
  this.company = comp;
 }
}
Now when we change the price we also notify the view by calling itemUpdated() method. So we rewrite the method findAndUpdateNonBindableStock as:
private function findAndUpdateNonBindableStock(ticker:String, updatedPrice:Number):void
{
   var nonBindableStock:NonBindableStock = nonBindableStocksDictionary[ticker] as                                                                    NonBindableStock;
   nonBindableStock.price = updatedPrice;
   nonBindableStocks.itemUpdated(nonBindableStock);
}
This will now update the view as well and we have removed the overhead of binding as well. I have optimized our stock ticker application and I hope you enjoyed this post. Let me know your feedback.


Designing and developing Stock Ticker application in Flex (Part Two)

As we mentioned in Part One there are two aspects yet to be optimized:

  1. Removing the Bindable tag as it is an overhead and a performance killer and control it ourselves.
  2. Controlling the data grid redraw as every price change is redrawing the whole grid.

Now as we know when we change the price of a stock it leads to collection change event and it leads to full redraw of the grid. There is one idea  here where we can prevent the collection change event of update kind and will make the item renderer responsible for the update part. In this case the datagrid will not be redrawn every time and will be a performance booster.

Another option I can think of is invalidateCell() method in the spark datagrid. 
public function invalidateCell(rowIndex:int, columnIndex:int):void

This method is handy when the specified cell is visible. If the specified cell is visible, it is redisplayed. If variableRowHeight=true, then doing so may cause the height of the corresponding row to change.
If columnIndex is -1, then the entire row is invalidated. Similarly if rowIndex is -1, then the entire column is invalidated.
This method should be called when there is a change to any aspect of the data provider item at rowIndex that might have some impact on the way the specified cell is displayed. Calling this method is similar to calling the dataProvider.itemUpdated() method, which advises the Grid that all rows displaying the specified item should be redisplayed. Using this method can be relatively efficient, since it narrows the scope of the change to a single cell.




This optimizes the redraw of the datagrid as well. Now we need to optimize the code so as to remove Bindable meta data tag. Part 3.

Designing and developing Stock Ticker application in Flex (Part One)

This post talks about many important points regarding the design and development of a stock ticker application in flex. The application is supposed to display the stocks in a datagrid or equivalent component. The price of the stocks will change and it will be changed immediately in datagrid. Let us first consider the performance aspects/assumptions:

1. There will be change in only one property of the stock and it will change very frequently.
2. For updating the price of a stock it needs to be searched among the list of stocks. The property ticker can come handy in identifying the stock out of the list.
3. We need one very effective way to search a stock quickly among a huge list of stocks.
4. We need to control the datagrid refresh and also control the binding events.

Before we go any further let us consider the aspect of locating a stock among the list of stocks. There can be thousands of stocks and looping over all of them to identify one of them can be a performance hit as it would take O(N) time and if these updates will be very frequent it is a serious problem. We can get O(1) time in a Dictionary which is equivalent to HashMap in Java. For time being assume that our stock value object is bindable (all properties as of now, we will improve is later).
[Bindable]
public class BindableStock
{
 public var price:Number;
 public var ticker:String;
 public var company:String;
  
 public function BindableStock(comp:String, tick:String, prc:Number)
 {
  this.price = prc;
  this.ticker = tick;
  this.company = comp;
 }
} 


Also assume that all the stocks are stored in an array collection in flex. Now change in price (or any other property) will lead to CollectionChangeEvent of update kind. This will further have a bunch of PropertyChangeEvent and the whole datagrid will be redrawn. We will optimize this redraw aspect later.

For optimizing the search we can store all these bindable stocks in dictionary as well. The key can be ticker property and value can be the whole stock object. Now when update comes we will locate them from dictionary and update the price of that stock.
private var bindableStocksDictionary:Dictionary;
[Bindable]private var bindableStocks:ArrayCollection = new ArrayCollection();
private function initializeBindableStocksList():void
{
      var stock1:BindableStock = new BindableStock("Infosys","INF",10.5);
      var stock2:BindableStock = new BindableStock("Oracle","ORC",12.3);
      var stock3:BindableStock = new BindableStock("Amazon","AMZ",23.4);
      var stock4:BindableStock = new BindableStock("Morgan Staley","MRS",39.7);
      var stock5:BindableStock = new BindableStock("Goldman Sachs","GS",13.8);
  
      bindableStocks.addItem(stock1);
      bindableStocks.addItem(stock2);
      bindableStocks.addItem(stock3);
      bindableStocks.addItem(stock4);
      bindableStocks.addItem(stock5);
    
      bindableStocksDictionary = new Dictionary();
      bindableStocksDictionary[stock1.ticker] = stock1;
      bindableStocksDictionary[stock2.ticker] = stock2;
      bindableStocksDictionary[stock3.ticker] = stock3;
      bindableStocksDictionary[stock4.ticker] = stock4;
      bindableStocksDictionary[stock5.ticker] = stock5;
  
}
We can bind the arraycollection bindableStocks to data provider of the datagrid or we can make it non-bindable and assign it at run time, but we need to track all the updates in that case. Now the find and update part will look like:
private function findAndUpdateBindableStock(ticker:String, updatedPrice:Number):void
{
 (bindableStocksDictionary[ticker] as BindableStock).price = updatedPrice;
}



Here we get the stock and update its price and it will be also be reflected in the datagrid. Here we need to track a Dictionary and an ArrayCollection. What about keeping one data structure that will server both the purpose. Here is the idea of DictionaryCollection and the code will be modified as:
[Bindable]private var bindableStocks:DictionaryCollection = new DictionaryCollection(null,"ticker");
private function initializeBindableStocksList():void
{
      var stock1:BindableStock = new BindableStock("Infosys","INF",10.5);
      var stock2:BindableStock = new BindableStock("Oracle","ORC",12.3);
      var stock3:BindableStock = new BindableStock("Amazon","AMZ",23.4);
      var stock4:BindableStock = new BindableStock("Morgan Staley","MRS",39.7);
      var stock5:BindableStock = new BindableStock("Goldman Sachs","GS",13.8);
  
      bindableStocks.addItem(stock1);
      bindableStocks.addItem(stock2);
      bindableStocks.addItem(stock3);
      bindableStocks.addItem(stock4);
      bindableStocks.addItem(stock5);
}
private function findAndUpdateBindableStock(ticker:String, updatedPrice:Number):void
{
 bindableStocks.getItemByKey(ticker).price = updatedPrice;
}
Now this looks clean and will be really optimum solution for searching and updating the stock. If we remove the Bindable tag over the stock value object the binding will not be triggered and nothing will work. There are two major things which are still pending:
1. Removing the Bindable tag as it is an overhead and a performance killer and control it ourselves.
2. Controlling the data grid redraw as every price change is redrawing the whole grid.

This will be continued in next part.

Wednesday, March 12, 2014

Why to avoid binding whenever possible?

Binding is one nice cool feature and it is used a lot and i really mean a lot!! We see that we get a collection (which is marked bindable mostly) of value objects where every value object is marked with RemoteAlias tag and Bindable tag. We change any of the property and it reflects. Isn't it cool? Yes it is but it comes with a serious performance issue.

Generally experienced programmers (Read it as experts) recommend to avoid binding as much as possible, if not entirely. This feature is overused, frankly. If we know that only 2 properties of the value object will change then making the whole value object bindable is overkill. When we mark the class with Bindable tag at top all its public properties become bindable which may not be needed all the time. It is better tom assign this tag to those properties that may change.

First of all avoid using Bindable it has serious performance problems if used a lot. It generates a lot of code which can have impact on performance. We can keep the value-objects in collection and can handle the job of updating the view manually. We can make use of itemUpdated() method to notify the view whenever the items change in collection. To keep track of changes in collection we can write a handler for collection change event. We should also avoid calling refresh() on array-collection until and unless we really need as this also is a performance problem.

Lets consider the following example taken from this presentation:

package valueObject

{

  [Bindable]

  public class Product {

    public var productName:String;

  }

}




This code generates a hell lot of code:

package valueObject
{
  import flash.events.IEventDispatcher;
  public class ProductManualBinding implements IEventDispatcher
{
private var dispatcher:flash.events.EventDispatcher = new flash.events.EventDispatcher(flash.events.IEventDispatcher(this ));
    [Bindable(event="propertyChange")]
public function get productName():String {
return _productName;
}
public function set productName(value:String):void {
        var oldValue:Object = _productName;
if (oldValue !== value) {
_productName = value;
dispatchEvent(mx.events.PropertyChangeEvent.
createUpdateEvent(this, "productName",oldValue,value));
}
    }
public function addEventListener(type:String,listener:Function,
useCapture:Boolean= false, priority:int= 0, weakRef:Boolean=false) :void 
{
      dispatcher.addEventListener(type,listener, useCapture,                 priority, weakRef);
}
public function dispatchEvent(event:flash.events.Event):Boolean
{
return dispatcher.dispatchEvent(event);
    }
public function hasEventListener(type:String):Boolean
{
return dispatcher.hasEventListener(type);
}
public function removeEventListener(type:String,
listener:Function, useCapture:Boolean = false):void 
{
        dispatcher.removeEventListener(type, listener, useCapture);
    }
public function willTrigger(type:String):Boolean
{
return dispatcher.willTrigger(type);
}
  }
}
First thing it generates a lot of code. Second thing we can observe is to specify the name of the event in Bindable tag is a good practice. That also has performance impact. The various scenarios are considered here.

If we really need binding then better option is to set binding using BindinhUtils class and get hold of change watcher. When we feel we don't need binding anymore we should remove it immediately by calling unwatch() method using the change watcher instance.

If we think carefully we will observe that most of the times we can skip binding. There are some common misuses of bindings explained in the link.

Also check: How to remove binding on an object?

Tuesday, March 11, 2014

How can we remove binding on Object in Flex?

Binding is one important feature of Flex. There are various ways to achieve it. If we use BindingUtils then we get an instance of ChangeWatcher class.
var watcherSetter:ChangeWatcher = 
                    BindingUtils.bindSetter(updateMyString, myTI, "text");
This class (ChangeWatcher) provides method unwatch() to remove the binding. We can also use ChangeWatcher directly as well.
var canWatch:Boolean = ChangeWatcher.canWatch(myObject, 'myProperty');
ChangeWatcher.watch(myObject, 'myProperty', myPropertyChangedHandler) 
BindingUtils is more like a wrapper over it and internally this class make use of ChangeWatcher only. Consider the bindProperty method:
public static function bindProperty(
                                site:Object, prop:String,
                                host:Object, chain:Object,
                                commitOnly:Boolean = false,
                               useWeakReference:Boolean = false):ChangeWatcher
{
    var w:ChangeWatcher =
       ChangeWatcher.watch(host, chain, null, commitOnly, useWeakReference);
        
    if (w != null)
    {
       var assign:Function = function(event:*):void
       {
          site[prop] = w.getValue();
       };
       w.setHandler(assign);
       assign(null);
    }
    return w;
}
and bindSetter method:
public static function bindSetter(setter:Function, host:Object,
                               chain:Object,
                               commitOnly:Boolean = false,
                              useWeakReference:Boolean = false):ChangeWatcher
{
    var w:ChangeWatcher =
       ChangeWatcher.watch(host, chain, null, commitOnly, useWeakReference);
        
    if (w != null)
    {
       var invoke:Function = function(event:*):void
       {
         setter(w.getValue());
       };
       w.setHandler(invoke);
       invoke(null);
    }
    return w;
}
Now the question asked now a days is how can we remove binding on an object? Before answering that lets try to understand what happens in Binding class:
public function Binding(document:Object, srcFunc:Function,
  			        destFunc:Function, destString:String,
				srcString:String = null)
    {
		super();

        this.document = document;
        this.srcFunc = srcFunc;
        this.destFunc = destFunc;
        this.destString = destString;
        this.srcString = srcString;

        if (this.srcFunc == null)
        {
            this.srcFunc = defaultSrcFunc;
        }

        if (this.destFunc == null)
        {
            this.destFunc = defaultDestFunc;
        }

        _isEnabled = true;
        isExecuting = false;
        isHandlingEvent = false;
        hasHadValue = false;
        uiComponentWatcher = -1;

        BindingManager.addBinding(document, destString, this);
    }   
In the constructor it sets various values and then makes call to addBinding() method in BindingManager class.
 public static function addBinding(document:Object, destStr:String,							  b:Binding):void
{
   if (!document._bindingsByDestination)
   {
      document._bindingsByDestination = {};
      document._bindingsBeginWithWord = {};
   }
   document._bindingsByDestination[destStr] = b;
   document._bindingsBeginWithWord[getFirstWord(destStr)] = true;
}

Actually all the bindings are stored in the following arrays:
  • mx_internal _bindings:Array
  • mx_internal _watchers:Array
  • mx_internal _bindingsByDefinitions
  • mx_internal _bindingsBeginWithWord
To remove binding we can use the following method as explained here:
public function removeBindings(object:Object):void
{
   if(!object) return
   if(object._bindings)
   {  
      for(var i:int = 0; i lt object._bindings.length; i++)
        object.bindings[i]= null;
      object._bindings.length = 0;
      object._bindings = null;
   }
   if(object._watchers)
   {
       for(i=0; i lt object._watchers.length; i++)
         object._watchers[i]= null;
       object._watchers.length = 0;
       object._watchers = null;
   }
   if(object._bindingsByDestination)
     object._bindingsByDestination = null;
   if(object._bindingsBeginWithWord
     object._bindingsBeginWithWord = null;
} 
I have used lt for less-than operator as it was getting formatting issues.

That is all and I hope you have enjoyed this post.