SlideShare a Scribd company logo
1 of 28
Download to read offline
Caching and
    Synchronization in Flex

    Zachary Pinter
    Senior Developer
    EffectiveUI
    360Flex




1
The Problem
    Common application data shown in multiple views, being manipulated by
    multiple users at roughly the same time.




2
Goals
    Fetch entities only once and only as needed.
    One definitive instance of a server-side entity.
    Update all relevant views when the server sends notice that an entity has
    changed.
    Server-side agnostic.




3
What’s the strategy?
    Store all fetched entities in a single cache (Dictionary).
    Bind the views to the cache.




4
What about memory use?
    public class WeakReference                 Allows cache values to be
    {                                          garbage-collected if they’re not
                                               being referenced anywhere else.
        private var dic:Dictionary;

        public function WeakReference(obj:*)
        {
           dic = new Dictionary(true); Text
           dic[obj] = 1;
        }

        public function getValue():* {
           for (var item:* in dic) {
              return item;
           }
           return null;
        }

    }


5
The Cache
    How do we add an entity to the cache?


    public class EntityCache
    {
       public function updateEntity(entity:BaseVO, ...):BaseVO
       {
          //...
       }
    }




6
Recurse through properties
    Adding a user to the cache also adds its address.
    UserVO
     id: 1
     firstname: “Zachary”
     lastname: “Pinter”                                 EntityCache
     address:                                            1: UserVO
       AddressVO                                         2: AddressVO
        id: 2
        line1: “4444 W 44th Ave”
        city: “Denver”
        state: “CO”




7
Recurse through properties
    Arrays behave the same way
    UserVO
     id: 1
     firstname: “Zachary”
     lastname: “Pinter”
     addresses: [                  EntityCache
       AddressVO
                                    1: UserVO
        id: 2
        label: “home”               2: AddressVO
        line1: “4444 W 44th Ave”    3: AddressVO
        city: “Denver”
        state: “CO”
      AddressVO
        id: 3
        label: “work”
        line1: “5555 W 55th Ave”
        city: “Denver”
        state: “CO”]
8
Finding an object’s properties
    Spring Actionscript (formally Prana)
    http://www.pranaframework.org/

    var type:Type = Type.forName(classname);

    for each (var accessor:Accessor in type.accessors) {
       if (accessor.isStatic == false && accessor.access.name == quot;readwritequot;) {
          result.push(accessor.name);
       }
    }
    return result;




9
Finding an object’s properties
     Source generator



     public class UserVO extends BaseVO {
        public var username : String;
        public var firstname : String;
        public var lastname : String;
        public var address : AddressVO;

         override public function getProperties():Array {
            return super.getProperties().concat(quot;usernamequot;,quot;firstnamequot;,quot;lastnamequot;,quot;addressquot;);
         }
     }




10
Updating the cache
     What if the entity is already in the cache?

         EntityCache                           EntityCache.updateEntity(
          1: UserVO(instance A)                  UserVO(instance B)
              id: 1                               id: 1
              firstname: “Robert”                  firstname: “Bob”
              lastname: “Smith”                   lastname: “Smith”
                                               )

                                                         Copy the properties from
                                                         instance B into instance A
                            EntityCache
                                                         Leave instance A in the
                             1: UserVO(instance A)
                                                         cache
                                 id: 1
                                 firstname: “Bob”         Discard instance B
                                 lastname: “Smith”

11
Updating the cache
     What about arrays?
     EntityCache
      UserVO
       id: 1
       firstname: “Zachary”
       lastname: “Pinter”            EntityCache.updateEntity(
       addresses: [                    AddressVO(instance B)
         AddressVO(instance A)
                                        id: 2
          id: 2
          label: “home”                 label: “home”
          line1: “4444 W 44th Ave”      line1: “3333 W 33rd Ave”
          city: “Denver”                city: “Denver”
          state: “CO”                   state: “CO”
        AddressVO                    )
          id: 3
          label: “work”
          line1: “5555 W 55th Ave”
          city: “Denver”
          state: “CO”]
12
Updating the cache
     What about arrays?

     UserVO
      id: 1                         Since we update the existing instance,
      firstname: “Zachary”           all references to it will see the update.
      lastname: “Pinter”
      addresses: [
        AddressVO(instance A)
         id: 2
         label: “home”
         line1: “3333 W 33rd Ave”
         city: “Denver”
         state: “CO”
       AddressVO
         id: 3
         label: “work”
         line1: “5555 W 55th Ave”
         city: “Denver”
         state: “CO”]
13
Updating the Cache
     The flip side
                                             UserVO
     EntityCache                              id: 5
      AddressVO(instance A)                   firstname: “Zachary”
                                              lastname: “Pinter”
        id: 2
                                              addresses: [
        label: “home”                           AddressVO(instance B)
        line1: “5555 W 55th Ave”                 id: 2
        city: “Denver”                           label: “home”
        state: “CO”                              line1: “6666 W 66th Ave”
                                                 city: “Denver”
                                                 state: “CO”
     Your cache already has an
                                               AddressVO
     AddressVO with id 2 in it, and you
                                                 id: 3
     add a new UserVO to the cache that
                                                 label: “work”
     references an updated instance of the
                                                 line1: “5555 W 55th Ave”
     AddressVO
                                                 city: “Denver”
                                                 state: “CO”]

14
Updating the Cache

                                         UserVO
     EntityCache                          id: 5
      AddressVO(instance A)               firstname: “Zachary”
                                          lastname: “Pinter”
        id: 2
                                          addresses: [
        label: “home”                       AddressVO(instance A)
        line1: “6666 W 66th Ave”             id: 2
        city: “Denver”                       label: “home”
        state: “CO”                          line1: “6666 W 66th Ave”
                                             city: “Denver”
                                             state: “CO”
     The AddressVO in the cache is         AddressVO
     updated and the AddressVO in            id: 3
     UserVO.addresses is replaced with       label: “work”
     the instance from the cache.            line1: “5555 W 55th Ave”
                                             city: “Denver”
                                             state: “CO”]

15
Updating the Cache
     Code looks something like this...

     if (obj is Array) {
        var arr:Array = obj as Array;
        for (var i:int=0;i<arr.length;i++) {
           if (arr[i] is BaseVO) {
              var res:BaseVO = updateEntity(arr[i] as BaseVO,...);
              if (res != null) arr[i] = res;
           }
        }
     }




16
Updating the Cache
     ArrayCollection’s are slightly trickier

     if (obj is ArrayCollection) {
        var ac:ArrayCollection = obj as ArrayCollection;
        ac.disableAutoUpdate();
        for (i=0;i<ac.length;i++) {
           if (ac.getItemAt(i) is BaseVO) {
              var res:BaseVO = updateEntity(ac.getItemAt(i) as BaseVO,...);
              if (res != null) {
                 ac.setItemAt(res,i);
              }
           }
        }
        ac.enableAutoUpdate();
     }




17
Now that we’ve added
     an entity to the cache...




18
The Cache
     How do we get an entity?
     What happens if we ask for an entity that isn’t in the cache?

     public class EntityCache
     {

         public function getEntity(id:String):EntityWrapper
         {
            //...
         }

     }




19
EntityWrapper
     [Bindable]
                                                    When requesting an entity, a
     public class EntityWrapper                     wrapper object is returned.
     {
        public var entityId:String;                 If that object is in the cache,
        public var entity:BaseVO;                   EntityWrapper.entity will have a
                                                    value.
         public function EntityWrapper(id:String)
         {                                          If the object is not in the cache,
            entityId = id;
         }                                          EntityWrapper.entity will be null
                                                    and a call to fetch the entity will
     }                                              be queued.




20
Using the Cache

     userWrapper = cache.getEntity(userid.text);


     <mx:Label text=quot;Username: {userWrapper.entity.username}quot;/>




21
Using the Cache - List Renderers
     Benefits
      ‣ Faster initial query since you’re only grabbing the id’s
      ‣ Rows are lazy-fetched as you scroll

     Drawbacks
      ‣ Sorting has to be handled by the server




22
Using the Cache - List Renderers
     What’s the code for the item renderer look like?



     override public function set data(val:Object):void
     {
        if(val != data){
           if (!val) {
              wrapper = null;
           } else {
              wrapper = cache.getEntity(val);
           }
           super.data = val;
        }
     }




23
Serverside Considerations
     What does this require of your backend infrastructure?
       ‣ Globally unique keys (or a way to fake it)
       ‣ Ability to get an entity by its key
       ‣ Ability to query for entities and only return their keys (used by lazy lists)


     Perks:
       ‣ Versioned entities
       ‣ Get multiple entities in a single call by passing multiple keys




24
Dictionary Keys
     Only one cache, need to prevent collisions
     Some Options:
       ‣ Globally unique sequence across all tables (UserVO with id 1, AddressVO with id 2)
       ‣ UUID’s (great for generating new id’s flex-side)
       ‣ Combine type with id (“UserVO-1”, “AddressVO-1”)




25
Demo




26
Questions?




27
Thanks!
     Zachary Pinter
     http://github.com/zpinter/cache-sync
     http://slideshare.net/zpinter
     http://zacharypinter.com
     http://effectiveui.com


     Twitter: zpinter




28

More Related Content

What's hot

Symfony Day 2010 Doctrine MongoDB ODM
Symfony Day 2010 Doctrine MongoDB ODMSymfony Day 2010 Doctrine MongoDB ODM
Symfony Day 2010 Doctrine MongoDB ODM
Jonathan Wage
 
Kai – An Open Source Implementation of Amazon’s Dynamo
Kai – An Open Source Implementation of Amazon’s DynamoKai – An Open Source Implementation of Amazon’s Dynamo
Kai – An Open Source Implementation of Amazon’s Dynamo
Takeru INOUE
 
Kai – An Open Source Implementation of Amazon’s Dynamo (in Japanese)
Kai – An Open Source Implementation of Amazon’s Dynamo (in Japanese)Kai – An Open Source Implementation of Amazon’s Dynamo (in Japanese)
Kai – An Open Source Implementation of Amazon’s Dynamo (in Japanese)
Takeru INOUE
 
Persistent Memoization with HTML5 indexedDB and jQuery Promises
Persistent Memoization with HTML5 indexedDB and jQuery PromisesPersistent Memoization with HTML5 indexedDB and jQuery Promises
Persistent Memoization with HTML5 indexedDB and jQuery Promises
Ray Bellis
 

What's hot (9)

Doctrine MongoDB Object Document Mapper
Doctrine MongoDB Object Document MapperDoctrine MongoDB Object Document Mapper
Doctrine MongoDB Object Document Mapper
 
Symfony Day 2010 Doctrine MongoDB ODM
Symfony Day 2010 Doctrine MongoDB ODMSymfony Day 2010 Doctrine MongoDB ODM
Symfony Day 2010 Doctrine MongoDB ODM
 
Kai – An Open Source Implementation of Amazon’s Dynamo
Kai – An Open Source Implementation of Amazon’s DynamoKai – An Open Source Implementation of Amazon’s Dynamo
Kai – An Open Source Implementation of Amazon’s Dynamo
 
Kai – An Open Source Implementation of Amazon’s Dynamo (in Japanese)
Kai – An Open Source Implementation of Amazon’s Dynamo (in Japanese)Kai – An Open Source Implementation of Amazon’s Dynamo (in Japanese)
Kai – An Open Source Implementation of Amazon’s Dynamo (in Japanese)
 
What do you mean, Backwards Compatibility?
What do you mean, Backwards Compatibility?What do you mean, Backwards Compatibility?
What do you mean, Backwards Compatibility?
 
2001: JNDI Its all in the Context
2001:  JNDI Its all in the Context2001:  JNDI Its all in the Context
2001: JNDI Its all in the Context
 
Persistent Memoization with HTML5 indexedDB and jQuery Promises
Persistent Memoization with HTML5 indexedDB and jQuery PromisesPersistent Memoization with HTML5 indexedDB and jQuery Promises
Persistent Memoization with HTML5 indexedDB and jQuery Promises
 
Dutch PHP Conference - PHPSpec 2 - The only Design Tool you need
Dutch PHP Conference - PHPSpec 2 - The only Design Tool you needDutch PHP Conference - PHPSpec 2 - The only Design Tool you need
Dutch PHP Conference - PHPSpec 2 - The only Design Tool you need
 
Reactive Access to MongoDB from Java 8
Reactive Access to MongoDB from Java 8Reactive Access to MongoDB from Java 8
Reactive Access to MongoDB from Java 8
 

Viewers also liked

презентация современные технологии в научных исследованиях
презентация  современные технологии в научных исследованияхпрезентация  современные технологии в научных исследованиях
презентация современные технологии в научных исследованиях
Anastasia Odintsova
 
влияние современных технологий на человека
влияние современных технологий на человекавлияние современных технологий на человека
влияние современных технологий на человека
loginik68
 
Performing Network & Security Analytics with Hadoop
Performing Network & Security Analytics with HadoopPerforming Network & Security Analytics with Hadoop
Performing Network & Security Analytics with Hadoop
DataWorks Summit
 
II-SDV 2014 Search and Data Mining Open Source Platforms (Patrick Beaucamp - ...
II-SDV 2014 Search and Data Mining Open Source Platforms (Patrick Beaucamp - ...II-SDV 2014 Search and Data Mining Open Source Platforms (Patrick Beaucamp - ...
II-SDV 2014 Search and Data Mining Open Source Platforms (Patrick Beaucamp - ...
Dr. Haxel Consult
 

Viewers also liked (16)

H is for_hadoop
H is for_hadoopH is for_hadoop
H is for_hadoop
 
презентация современные технологии в научных исследованиях
презентация  современные технологии в научных исследованияхпрезентация  современные технологии в научных исследованиях
презентация современные технологии в научных исследованиях
 
влияние современных технологий на человека
влияние современных технологий на человекавлияние современных технологий на человека
влияние современных технологий на человека
 
Hadoop - Lessons Learned
Hadoop - Lessons LearnedHadoop - Lessons Learned
Hadoop - Lessons Learned
 
EMC Storage Redefine FILE
EMC Storage Redefine FILEEMC Storage Redefine FILE
EMC Storage Redefine FILE
 
Performing Network & Security Analytics with Hadoop
Performing Network & Security Analytics with HadoopPerforming Network & Security Analytics with Hadoop
Performing Network & Security Analytics with Hadoop
 
Altic's big analytics stack, Charly Clairmont, Altic.
Altic's big analytics stack, Charly Clairmont, Altic.Altic's big analytics stack, Charly Clairmont, Altic.
Altic's big analytics stack, Charly Clairmont, Altic.
 
Pivotal: Hadoop for Powerful Processing of Unstructured Data for Valuable Ins...
Pivotal: Hadoop for Powerful Processing of Unstructured Data for Valuable Ins...Pivotal: Hadoop for Powerful Processing of Unstructured Data for Valuable Ins...
Pivotal: Hadoop for Powerful Processing of Unstructured Data for Valuable Ins...
 
Hadoop World 2011: Data Mining in Hadoop, Making Sense of it in Mahout! - Mic...
Hadoop World 2011: Data Mining in Hadoop, Making Sense of it in Mahout! - Mic...Hadoop World 2011: Data Mining in Hadoop, Making Sense of it in Mahout! - Mic...
Hadoop World 2011: Data Mining in Hadoop, Making Sense of it in Mahout! - Mic...
 
Introduction to Datamining Concept and Techniques
Introduction to Datamining Concept and TechniquesIntroduction to Datamining Concept and Techniques
Introduction to Datamining Concept and Techniques
 
II-SDV 2014 Search and Data Mining Open Source Platforms (Patrick Beaucamp - ...
II-SDV 2014 Search and Data Mining Open Source Platforms (Patrick Beaucamp - ...II-SDV 2014 Search and Data Mining Open Source Platforms (Patrick Beaucamp - ...
II-SDV 2014 Search and Data Mining Open Source Platforms (Patrick Beaucamp - ...
 
A survey of 2013 data science salary survey”
A survey of   2013 data science salary survey”A survey of   2013 data science salary survey”
A survey of 2013 data science salary survey”
 
An Introduction to the World of Hadoop
An Introduction to the World of HadoopAn Introduction to the World of Hadoop
An Introduction to the World of Hadoop
 
Apriori algorithm
Apriori algorithmApriori algorithm
Apriori algorithm
 
Apriori Algorithm
Apriori AlgorithmApriori Algorithm
Apriori Algorithm
 
Data mining
Data miningData mining
Data mining
 

Similar to Zach Pinter - Caching and Synchronization with Flex

20101017 program analysis_for_security_livshits_lecture04_nozzle
20101017 program analysis_for_security_livshits_lecture04_nozzle20101017 program analysis_for_security_livshits_lecture04_nozzle
20101017 program analysis_for_security_livshits_lecture04_nozzle
Computer Science Club
 
Scaling Twitter 12758
Scaling Twitter 12758Scaling Twitter 12758
Scaling Twitter 12758
davidblum
 
Industroyer: biggest threat to industrial control systems since Stuxnet by An...
Industroyer: biggest threat to industrial control systems since Stuxnet by An...Industroyer: biggest threat to industrial control systems since Stuxnet by An...
Industroyer: biggest threat to industrial control systems since Stuxnet by An...
CODE BLUE
 
javascript teach
javascript teachjavascript teach
javascript teach
guest3732fa
 
JSBootcamp_White
JSBootcamp_WhiteJSBootcamp_White
JSBootcamp_White
guest3732fa
 

Similar to Zach Pinter - Caching and Synchronization with Flex (20)

Intro to Cocoa KVC/KVO and Bindings
Intro to Cocoa KVC/KVO and BindingsIntro to Cocoa KVC/KVO and Bindings
Intro to Cocoa KVC/KVO and Bindings
 
How Scala code is expressed in the JVM
How Scala code is expressed in the JVMHow Scala code is expressed in the JVM
How Scala code is expressed in the JVM
 
Javascript The Good Parts
Javascript The Good PartsJavascript The Good Parts
Javascript The Good Parts
 
Quick Intro To JRuby
Quick Intro To JRubyQuick Intro To JRuby
Quick Intro To JRuby
 
Vidoop CouchDB Talk
Vidoop CouchDB TalkVidoop CouchDB Talk
Vidoop CouchDB Talk
 
BADCamp 2008 DB Sync
BADCamp 2008 DB SyncBADCamp 2008 DB Sync
BADCamp 2008 DB Sync
 
DPC2007 PHP And Oracle (Kuassi Mensah)
DPC2007 PHP And Oracle (Kuassi Mensah)DPC2007 PHP And Oracle (Kuassi Mensah)
DPC2007 PHP And Oracle (Kuassi Mensah)
 
Ugo Cei Presentation
Ugo Cei PresentationUgo Cei Presentation
Ugo Cei Presentation
 
20101017 program analysis_for_security_livshits_lecture04_nozzle
20101017 program analysis_for_security_livshits_lecture04_nozzle20101017 program analysis_for_security_livshits_lecture04_nozzle
20101017 program analysis_for_security_livshits_lecture04_nozzle
 
Pyruvate, a reasonably fast, non-blocking, multithreaded WSGI server
Pyruvate, a reasonably fast, non-blocking, multithreaded WSGI serverPyruvate, a reasonably fast, non-blocking, multithreaded WSGI server
Pyruvate, a reasonably fast, non-blocking, multithreaded WSGI server
 
Windows Azure Storage
Windows Azure StorageWindows Azure Storage
Windows Azure Storage
 
MySQL Proxy tutorial
MySQL Proxy tutorialMySQL Proxy tutorial
MySQL Proxy tutorial
 
Grizzly1.9.3x
Grizzly1.9.3xGrizzly1.9.3x
Grizzly1.9.3x
 
Scaling Twitter 12758
Scaling Twitter 12758Scaling Twitter 12758
Scaling Twitter 12758
 
Industroyer: biggest threat to industrial control systems since Stuxnet by An...
Industroyer: biggest threat to industrial control systems since Stuxnet by An...Industroyer: biggest threat to industrial control systems since Stuxnet by An...
Industroyer: biggest threat to industrial control systems since Stuxnet by An...
 
jQuery Presentation to Rails Developers
jQuery Presentation to Rails DevelopersjQuery Presentation to Rails Developers
jQuery Presentation to Rails Developers
 
Ruby 2.4 Internals
Ruby 2.4 InternalsRuby 2.4 Internals
Ruby 2.4 Internals
 
Couchdb: No SQL? No driver? No problem
Couchdb: No SQL? No driver? No problemCouchdb: No SQL? No driver? No problem
Couchdb: No SQL? No driver? No problem
 
javascript teach
javascript teachjavascript teach
javascript teach
 
JSBootcamp_White
JSBootcamp_WhiteJSBootcamp_White
JSBootcamp_White
 

More from 360|Conferences

Giorgio Natilli - Blaze DS Connectivity Framework
Giorgio Natilli - Blaze DS Connectivity FrameworkGiorgio Natilli - Blaze DS Connectivity Framework
Giorgio Natilli - Blaze DS Connectivity Framework
360|Conferences
 

More from 360|Conferences (20)

InsideMobile Keynote
InsideMobile KeynoteInsideMobile Keynote
InsideMobile Keynote
 
Metaio Mobile Augmented Reality
Metaio Mobile Augmented RealityMetaio Mobile Augmented Reality
Metaio Mobile Augmented Reality
 
Web Os Hands On
Web Os Hands OnWeb Os Hands On
Web Os Hands On
 
Mobile Apps- Business Toolkit for the Manager
Mobile Apps- Business Toolkit for the ManagerMobile Apps- Business Toolkit for the Manager
Mobile Apps- Business Toolkit for the Manager
 
Making Real Money with Mobile Apps
Making Real Money with Mobile AppsMaking Real Money with Mobile Apps
Making Real Money with Mobile Apps
 
Unlocking Android
Unlocking AndroidUnlocking Android
Unlocking Android
 
Inside Mobile Widgets Publish
Inside Mobile Widgets PublishInside Mobile Widgets Publish
Inside Mobile Widgets Publish
 
You Know WebOS
You Know WebOSYou Know WebOS
You Know WebOS
 
Ignite Denver 4 Master Deck
Ignite Denver 4 Master DeckIgnite Denver 4 Master Deck
Ignite Denver 4 Master Deck
 
Oğuz Demirkapı - Hands On Training: Creating Our First i18N Flex Application ...
Oğuz	Demirkapı - Hands On Training: Creating Our First i18N Flex Application ...Oğuz	Demirkapı - Hands On Training: Creating Our First i18N Flex Application ...
Oğuz Demirkapı - Hands On Training: Creating Our First i18N Flex Application ...
 
Tyler Wright - Undo History with Flight
Tyler Wright - Undo History with FlightTyler Wright - Undo History with Flight
Tyler Wright - Undo History with Flight
 
Chad Udell - Developers are from Mars, Designers are from Venus
Chad Udell - Developers are from Mars, Designers are from VenusChad Udell - Developers are from Mars, Designers are from Venus
Chad Udell - Developers are from Mars, Designers are from Venus
 
Mansour Raad & Anthony Jayaprakash - Yet Another Mapping Framework, NOT!
Mansour Raad & Anthony Jayaprakash - Yet Another Mapping Framework, NOT!Mansour Raad & Anthony Jayaprakash - Yet Another Mapping Framework, NOT!
Mansour Raad & Anthony Jayaprakash - Yet Another Mapping Framework, NOT!
 
Erik Loehfelm - Experience Design with Flash Catalyst and Flex Gumbo
Erik Loehfelm - Experience Design with Flash Catalyst and Flex GumboErik Loehfelm - Experience Design with Flash Catalyst and Flex Gumbo
Erik Loehfelm - Experience Design with Flash Catalyst and Flex Gumbo
 
Ryan Phelan - Bending and Flexing
Ryan Phelan - Bending and FlexingRyan Phelan - Bending and Flexing
Ryan Phelan - Bending and Flexing
 
Giorgio Natilli - Blaze DS Connectivity Framework
Giorgio Natilli - Blaze DS Connectivity FrameworkGiorgio Natilli - Blaze DS Connectivity Framework
Giorgio Natilli - Blaze DS Connectivity Framework
 
Douglas Knudsen - Great Mash Up
Douglas Knudsen - Great Mash UpDouglas Knudsen - Great Mash Up
Douglas Knudsen - Great Mash Up
 
Wes Leonardo - Putting AIR into your Application
Wes Leonardo - Putting AIR into your ApplicationWes Leonardo - Putting AIR into your Application
Wes Leonardo - Putting AIR into your Application
 
Samuel Asher Rivello - PureMVC Hands On Part 1
Samuel Asher Rivello - PureMVC Hands On Part 1Samuel Asher Rivello - PureMVC Hands On Part 1
Samuel Asher Rivello - PureMVC Hands On Part 1
 
Adrian Pomilio - Flex Ajax Bridge and Legacy Applications
Adrian Pomilio - Flex Ajax Bridge and Legacy ApplicationsAdrian Pomilio - Flex Ajax Bridge and Legacy Applications
Adrian Pomilio - Flex Ajax Bridge and Legacy Applications
 

Recently uploaded

Structuring Teams and Portfolios for Success
Structuring Teams and Portfolios for SuccessStructuring Teams and Portfolios for Success
Structuring Teams and Portfolios for Success
UXDXConf
 
Breaking Down the Flutterwave Scandal What You Need to Know.pdf
Breaking Down the Flutterwave Scandal What You Need to Know.pdfBreaking Down the Flutterwave Scandal What You Need to Know.pdf
Breaking Down the Flutterwave Scandal What You Need to Know.pdf
UK Journal
 

Recently uploaded (20)

Powerful Start- the Key to Project Success, Barbara Laskowska
Powerful Start- the Key to Project Success, Barbara LaskowskaPowerful Start- the Key to Project Success, Barbara Laskowska
Powerful Start- the Key to Project Success, Barbara Laskowska
 
Choosing the Right FDO Deployment Model for Your Application _ Geoffrey at In...
Choosing the Right FDO Deployment Model for Your Application _ Geoffrey at In...Choosing the Right FDO Deployment Model for Your Application _ Geoffrey at In...
Choosing the Right FDO Deployment Model for Your Application _ Geoffrey at In...
 
Google I/O Extended 2024 Warsaw
Google I/O Extended 2024 WarsawGoogle I/O Extended 2024 Warsaw
Google I/O Extended 2024 Warsaw
 
ERP Contender Series: Acumatica vs. Sage Intacct
ERP Contender Series: Acumatica vs. Sage IntacctERP Contender Series: Acumatica vs. Sage Intacct
ERP Contender Series: Acumatica vs. Sage Intacct
 
Integrating Telephony Systems with Salesforce: Insights and Considerations, B...
Integrating Telephony Systems with Salesforce: Insights and Considerations, B...Integrating Telephony Systems with Salesforce: Insights and Considerations, B...
Integrating Telephony Systems with Salesforce: Insights and Considerations, B...
 
IESVE for Early Stage Design and Planning
IESVE for Early Stage Design and PlanningIESVE for Early Stage Design and Planning
IESVE for Early Stage Design and Planning
 
FDO for Camera, Sensor and Networking Device – Commercial Solutions from VinC...
FDO for Camera, Sensor and Networking Device – Commercial Solutions from VinC...FDO for Camera, Sensor and Networking Device – Commercial Solutions from VinC...
FDO for Camera, Sensor and Networking Device – Commercial Solutions from VinC...
 
WebAssembly is Key to Better LLM Performance
WebAssembly is Key to Better LLM PerformanceWebAssembly is Key to Better LLM Performance
WebAssembly is Key to Better LLM Performance
 
Structuring Teams and Portfolios for Success
Structuring Teams and Portfolios for SuccessStructuring Teams and Portfolios for Success
Structuring Teams and Portfolios for Success
 
Simplified FDO Manufacturing Flow with TPMs _ Liam at Infineon.pdf
Simplified FDO Manufacturing Flow with TPMs _ Liam at Infineon.pdfSimplified FDO Manufacturing Flow with TPMs _ Liam at Infineon.pdf
Simplified FDO Manufacturing Flow with TPMs _ Liam at Infineon.pdf
 
ECS 2024 Teams Premium - Pretty Secure
ECS 2024   Teams Premium - Pretty SecureECS 2024   Teams Premium - Pretty Secure
ECS 2024 Teams Premium - Pretty Secure
 
Breaking Down the Flutterwave Scandal What You Need to Know.pdf
Breaking Down the Flutterwave Scandal What You Need to Know.pdfBreaking Down the Flutterwave Scandal What You Need to Know.pdf
Breaking Down the Flutterwave Scandal What You Need to Know.pdf
 
Introduction to FDO and How It works Applications _ Richard at FIDO Alliance.pdf
Introduction to FDO and How It works Applications _ Richard at FIDO Alliance.pdfIntroduction to FDO and How It works Applications _ Richard at FIDO Alliance.pdf
Introduction to FDO and How It works Applications _ Richard at FIDO Alliance.pdf
 
Where to Learn More About FDO _ Richard at FIDO Alliance.pdf
Where to Learn More About FDO _ Richard at FIDO Alliance.pdfWhere to Learn More About FDO _ Richard at FIDO Alliance.pdf
Where to Learn More About FDO _ Richard at FIDO Alliance.pdf
 
What's New in Teams Calling, Meetings and Devices April 2024
What's New in Teams Calling, Meetings and Devices April 2024What's New in Teams Calling, Meetings and Devices April 2024
What's New in Teams Calling, Meetings and Devices April 2024
 
1111 ChatGPT Prompts PDF Free Download - Prompts for ChatGPT
1111 ChatGPT Prompts PDF Free Download - Prompts for ChatGPT1111 ChatGPT Prompts PDF Free Download - Prompts for ChatGPT
1111 ChatGPT Prompts PDF Free Download - Prompts for ChatGPT
 
How Red Hat Uses FDO in Device Lifecycle _ Costin and Vitaliy at Red Hat.pdf
How Red Hat Uses FDO in Device Lifecycle _ Costin and Vitaliy at Red Hat.pdfHow Red Hat Uses FDO in Device Lifecycle _ Costin and Vitaliy at Red Hat.pdf
How Red Hat Uses FDO in Device Lifecycle _ Costin and Vitaliy at Red Hat.pdf
 
Secure Zero Touch enabled Edge compute with Dell NativeEdge via FDO _ Brad at...
Secure Zero Touch enabled Edge compute with Dell NativeEdge via FDO _ Brad at...Secure Zero Touch enabled Edge compute with Dell NativeEdge via FDO _ Brad at...
Secure Zero Touch enabled Edge compute with Dell NativeEdge via FDO _ Brad at...
 
ASRock Industrial FDO Solutions in Action for Industrial Edge AI _ Kenny at A...
ASRock Industrial FDO Solutions in Action for Industrial Edge AI _ Kenny at A...ASRock Industrial FDO Solutions in Action for Industrial Edge AI _ Kenny at A...
ASRock Industrial FDO Solutions in Action for Industrial Edge AI _ Kenny at A...
 
Syngulon - Selection technology May 2024.pdf
Syngulon - Selection technology May 2024.pdfSyngulon - Selection technology May 2024.pdf
Syngulon - Selection technology May 2024.pdf
 

Zach Pinter - Caching and Synchronization with Flex

  • 1. Caching and Synchronization in Flex Zachary Pinter Senior Developer EffectiveUI 360Flex 1
  • 2. The Problem Common application data shown in multiple views, being manipulated by multiple users at roughly the same time. 2
  • 3. Goals Fetch entities only once and only as needed. One definitive instance of a server-side entity. Update all relevant views when the server sends notice that an entity has changed. Server-side agnostic. 3
  • 4. What’s the strategy? Store all fetched entities in a single cache (Dictionary). Bind the views to the cache. 4
  • 5. What about memory use? public class WeakReference Allows cache values to be { garbage-collected if they’re not being referenced anywhere else. private var dic:Dictionary; public function WeakReference(obj:*) { dic = new Dictionary(true); Text dic[obj] = 1; } public function getValue():* { for (var item:* in dic) { return item; } return null; } } 5
  • 6. The Cache How do we add an entity to the cache? public class EntityCache { public function updateEntity(entity:BaseVO, ...):BaseVO { //... } } 6
  • 7. Recurse through properties Adding a user to the cache also adds its address. UserVO id: 1 firstname: “Zachary” lastname: “Pinter” EntityCache address: 1: UserVO AddressVO 2: AddressVO id: 2 line1: “4444 W 44th Ave” city: “Denver” state: “CO” 7
  • 8. Recurse through properties Arrays behave the same way UserVO id: 1 firstname: “Zachary” lastname: “Pinter” addresses: [ EntityCache AddressVO 1: UserVO id: 2 label: “home” 2: AddressVO line1: “4444 W 44th Ave” 3: AddressVO city: “Denver” state: “CO” AddressVO id: 3 label: “work” line1: “5555 W 55th Ave” city: “Denver” state: “CO”] 8
  • 9. Finding an object’s properties Spring Actionscript (formally Prana) http://www.pranaframework.org/ var type:Type = Type.forName(classname); for each (var accessor:Accessor in type.accessors) { if (accessor.isStatic == false && accessor.access.name == quot;readwritequot;) { result.push(accessor.name); } } return result; 9
  • 10. Finding an object’s properties Source generator public class UserVO extends BaseVO { public var username : String; public var firstname : String; public var lastname : String; public var address : AddressVO; override public function getProperties():Array { return super.getProperties().concat(quot;usernamequot;,quot;firstnamequot;,quot;lastnamequot;,quot;addressquot;); } } 10
  • 11. Updating the cache What if the entity is already in the cache? EntityCache EntityCache.updateEntity( 1: UserVO(instance A) UserVO(instance B) id: 1 id: 1 firstname: “Robert” firstname: “Bob” lastname: “Smith” lastname: “Smith” ) Copy the properties from instance B into instance A EntityCache Leave instance A in the 1: UserVO(instance A) cache id: 1 firstname: “Bob” Discard instance B lastname: “Smith” 11
  • 12. Updating the cache What about arrays? EntityCache UserVO id: 1 firstname: “Zachary” lastname: “Pinter” EntityCache.updateEntity( addresses: [ AddressVO(instance B) AddressVO(instance A) id: 2 id: 2 label: “home” label: “home” line1: “4444 W 44th Ave” line1: “3333 W 33rd Ave” city: “Denver” city: “Denver” state: “CO” state: “CO” AddressVO ) id: 3 label: “work” line1: “5555 W 55th Ave” city: “Denver” state: “CO”] 12
  • 13. Updating the cache What about arrays? UserVO id: 1 Since we update the existing instance, firstname: “Zachary” all references to it will see the update. lastname: “Pinter” addresses: [ AddressVO(instance A) id: 2 label: “home” line1: “3333 W 33rd Ave” city: “Denver” state: “CO” AddressVO id: 3 label: “work” line1: “5555 W 55th Ave” city: “Denver” state: “CO”] 13
  • 14. Updating the Cache The flip side UserVO EntityCache id: 5 AddressVO(instance A) firstname: “Zachary” lastname: “Pinter” id: 2 addresses: [ label: “home” AddressVO(instance B) line1: “5555 W 55th Ave” id: 2 city: “Denver” label: “home” state: “CO” line1: “6666 W 66th Ave” city: “Denver” state: “CO” Your cache already has an AddressVO AddressVO with id 2 in it, and you id: 3 add a new UserVO to the cache that label: “work” references an updated instance of the line1: “5555 W 55th Ave” AddressVO city: “Denver” state: “CO”] 14
  • 15. Updating the Cache UserVO EntityCache id: 5 AddressVO(instance A) firstname: “Zachary” lastname: “Pinter” id: 2 addresses: [ label: “home” AddressVO(instance A) line1: “6666 W 66th Ave” id: 2 city: “Denver” label: “home” state: “CO” line1: “6666 W 66th Ave” city: “Denver” state: “CO” The AddressVO in the cache is AddressVO updated and the AddressVO in id: 3 UserVO.addresses is replaced with label: “work” the instance from the cache. line1: “5555 W 55th Ave” city: “Denver” state: “CO”] 15
  • 16. Updating the Cache Code looks something like this... if (obj is Array) { var arr:Array = obj as Array; for (var i:int=0;i<arr.length;i++) { if (arr[i] is BaseVO) { var res:BaseVO = updateEntity(arr[i] as BaseVO,...); if (res != null) arr[i] = res; } } } 16
  • 17. Updating the Cache ArrayCollection’s are slightly trickier if (obj is ArrayCollection) { var ac:ArrayCollection = obj as ArrayCollection; ac.disableAutoUpdate(); for (i=0;i<ac.length;i++) { if (ac.getItemAt(i) is BaseVO) { var res:BaseVO = updateEntity(ac.getItemAt(i) as BaseVO,...); if (res != null) { ac.setItemAt(res,i); } } } ac.enableAutoUpdate(); } 17
  • 18. Now that we’ve added an entity to the cache... 18
  • 19. The Cache How do we get an entity? What happens if we ask for an entity that isn’t in the cache? public class EntityCache { public function getEntity(id:String):EntityWrapper { //... } } 19
  • 20. EntityWrapper [Bindable] When requesting an entity, a public class EntityWrapper wrapper object is returned. { public var entityId:String; If that object is in the cache, public var entity:BaseVO; EntityWrapper.entity will have a value. public function EntityWrapper(id:String) { If the object is not in the cache, entityId = id; } EntityWrapper.entity will be null and a call to fetch the entity will } be queued. 20
  • 21. Using the Cache userWrapper = cache.getEntity(userid.text); <mx:Label text=quot;Username: {userWrapper.entity.username}quot;/> 21
  • 22. Using the Cache - List Renderers Benefits ‣ Faster initial query since you’re only grabbing the id’s ‣ Rows are lazy-fetched as you scroll Drawbacks ‣ Sorting has to be handled by the server 22
  • 23. Using the Cache - List Renderers What’s the code for the item renderer look like? override public function set data(val:Object):void { if(val != data){ if (!val) { wrapper = null; } else { wrapper = cache.getEntity(val); } super.data = val; } } 23
  • 24. Serverside Considerations What does this require of your backend infrastructure? ‣ Globally unique keys (or a way to fake it) ‣ Ability to get an entity by its key ‣ Ability to query for entities and only return their keys (used by lazy lists) Perks: ‣ Versioned entities ‣ Get multiple entities in a single call by passing multiple keys 24
  • 25. Dictionary Keys Only one cache, need to prevent collisions Some Options: ‣ Globally unique sequence across all tables (UserVO with id 1, AddressVO with id 2) ‣ UUID’s (great for generating new id’s flex-side) ‣ Combine type with id (“UserVO-1”, “AddressVO-1”) 25
  • 28. Thanks! Zachary Pinter http://github.com/zpinter/cache-sync http://slideshare.net/zpinter http://zacharypinter.com http://effectiveui.com Twitter: zpinter 28