Object Oriented Methods Architectural Patterns 3 Spring 2009
Object Oriented Methods Architectural Patterns 3 Spring 2009 Computer Science Department, TUC-N
Content • Patterns for Enterprise Application Architecture [Fowler] - continued – Data Source Patterns – Concurrency Patterns Spring 2009 Computer Science Department, TUC-N
References • Martin Fowler et. al, Patterns of Enterprise Application Architecture, Addison Wesley, 2003 [Fowler] Spring 2009 Computer Science Department, TUC-N
Data Source Patterns • Pure Data Source Patterns – Gateways • Row Data Gateway (RDG) • Table Data Gateway (TDG) – Data Mapper • Hybrid Data Source Pattern (discussed) – Active Record – Table Module Spring 2009 Computer Science Department, TUC-N
Data Source Patterns • Hide SQL. • Provide an abstraction for – One data row. – A collection of data row(s). • OR mapping problems – Links – Inheritance Spring 2009 Computer Science Department, TUC-N
Table Data Gateway Fowler: An object that acts as a gateway to a database table. One instance handles all the rows in the table. A TDG hides all the SQL for accessing a single DB table or DB view: selects, updates, deletes. Spring 2009 Computer Science Department, TUC-N
TDG Spring 2009 Computer Science Department, TUC-N
Features • Find, insert, update, delete methods • Challenge: how it returns information from a query ? – Data Transfer Object – Record Set • Goes well with Table Module • Suitable for Transaction Scripts Spring 2009 Computer Science Department, TUC-N
Using ADO. NET Data. Sets Spring 2009 Computer Science Department, TUC-N
Implementation class Data. Set. Holder. . . public Data. Set Data = new Data. Set(); private Hashtable Data. Adapters = new Hashtable(); class Data. Gateway. . . public Data. Set. Holder; public Data. Set Data { get {return Holder. Data; } } Spring 2009 Computer Science Department, TUC-N
Implementing find behavior class Data. Gateway. . . public void Load. All() { String command. String = String. Format("select * from {0}", Table. Name); Holder. Fill. Data(command. String, Table. Name); } public void Load. Where(String where. Clause) { String command. String = String. Format("select * from {0} where {1}", Table. Name, where. Clause); Holder. Fill. Data(command. String, Table. Name); } abstract public String Table. Name {get; } Spring 2009 Computer Science Department, TUC-N
Implementation continued class Person. Gateway. . . public override String Table. Name { get {return "Person"; } } class Data. Set. Holder. . . public void Fill. Data(String query, String table. Name) { if (Data. Adapters. Contains(table. Name)) throw new Mutliple. Load. Exception(); Ole. Db. Data. Adapter da = new Ole. Db. Data. Adapter(query, DB. Connection); Ole. Db. Command. Builder builder = new Ole. Db. Command. Builder(da); da. Fill(Data, table. Name); Data. Adapters. Add(table. Name, da); } Spring 2009 Computer Science Department, TUC-N
Row Data Gateway • An object that acts as a single record in the data source – There is one instance per row • Fowler RDG combines two roles Class …Finder with find(id): Gateway method which returns the ‘object’ Class …Gateway which is the ‘object’ Spring 2009 Computer Science Department, TUC-N
Row Data Gateway Spring 2009 Computer Science Department, TUC-N
How it works? • Separate data access code from Domain logic • type conversion from the data source types to the in-memory types • works particularly well for Transaction Scripts • where to put the find operations that generate the Row Data ? Spring 2009 Computer Science Department, TUC-N
How it works? • static find methods -> hinders polymorphism • separate finder objects • each table in a relational database will have: – one finder class – one gateway class for the results. Spring 2009 Computer Science Department, TUC-N
RDG behavior Spring 2009 Computer Science Department, TUC-N
Implementation class Person. Gateway. . . private String last. Name; private String first. Name; private int number. Of. Dependents; public String get. Last. Name() { return last. Name; } public void set. Last. Name(String last. Name) { this. last. Name = last. Name; } … private static final String update. Statement. String = "UPDATE people " + " set lastname = ? , firstname = ? , number_of_dependents = ? " + " where id = ? "; public void update() { …} … Spring 2009 Computer Science Department, TUC-N
Person. Finder class Person. Finder. . . private final static String find. Statement. String = "SELECT id, lastname, firstname, number_of_dependents " + " from people " + " WHERE id = ? "; public Person. Gateway find(Long id) { Person. Gateway result = (Person. Gateway)Registry. get. Person(id); if (result != null) return result; try { find. Statement = DB. prepare(find. Statement. String); find. Statement. set. Long(1, id. long. Value()); rs = find. Statement. execute. Query(); rs. next(); result = Person. Gateway. load(rs); return result; } catch (SQLException e) { throw new Application. Exception(e); } Spring 2009 Computer Science Department, TUC-N
Using RDG in Transaction Scripts Person. Finder finder = new Person. Finder(); Iterator people = finder. find. Responsibles(). iterator(); String. Buffer result = new String. Buffer(); while (people. has. Next()) { Person. Gateway each = (Person. Gateway) people. next(); result. append(each. get. Last. Name()); result. append("t"); result. append(each. get. First. Name()); result. append("t"); result. append(String. value. Of(each. get. Number. Of. Depend ents())); result. append("n"); } return result. to. String(); Spring 2009 Computer Science Department, TUC-N
Using RDG as a holder for the domain object class Person. . . private Person. Gateway data; public Person(Person. Gateway data) { this. data = data; } public int get. Number. Of. Dependents() { return data. get. Number. Of. Dependents(); } Spring 2009 Computer Science Department, TUC-N
Data Mappers • Acts as an intermediary between Domain Models and the database. • Allows Domain Models and Data Source classes to be independent of each other Spring 2009 Computer Science Department, TUC-N
Data Mapper Layer … • Can either – Access the database itself, or – Make use of a Table Data Gateway. • Does not contain Domain Logic. • When it uses a TDG, the Data Mapper can be placed in the (lower) Domain layer. Spring 2009 Computer Science Department, TUC-N
How it works – retrieving data Spring 2009 Computer Science Department, TUC-N
Finding objects Spring 2009 Computer Science Department, TUC-N
How it works – updating data Spring 2009 Computer Science Department, TUC-N
Features • Independent database schema and object model • Extra layer • Works well with Domain Model Spring 2009 Computer Science Department, TUC-N
Implementation class Person. . . private String last. Name; private String first. Name; private int number. Of. Dependents; create table people (ID int primary key, lastname varchar, firstname varchar, number_of_dependents int) Spring 2009 Computer Science Department, TUC-N
Mapper class implements finder class Person. Mapper. . . protected String find. Statement() { return "SELECT " + COLUMNS + " FROM people" + " WHERE id = ? "; } public static final String COLUMNS = " id, lastname, firstname, number_of_dependents "; public Person find(Long id) { return (Person) abstract. Find(id); } Spring 2009 Computer Science Department, TUC-N
Abstract. Mapper class Abstract. Mapper. . . protected Map loaded. Map = new Hash. Map(); abstract protected String find. Statement(); protected Domain. Object abstract. Find(Long id) { Domain. Object result = (Domain. Object) loaded. Map. get(id); if (result != null) return result; Prepared. Statement find. Statement = null; try { find. Statement = DB. prepare(find. Statement()); find. Statement. set. Long(1, id. long. Value()); Result. Set rs = find. Statement. execute. Query(); rs. next(); result = load(rs); return result; } catch (SQLException e) { throw new Application. Exception(e); } finally { DB. clean. Up(find. Statement); } } Spring 2009 Computer Science Department, TUC-N
Load method in Abstract. Mapper class Abstract. Mapper. . . protected Domain. Object load(Result. Set rs) throws SQLException { Long id = new Long(rs. get. Long(1)); if (loaded. Map. contains. Key(id)) return (Domain. Object) loaded. Map. get(id); Domain. Object result = do. Load(id, rs); loaded. Map. put(id, result); return result; } abstract protected Domain. Object do. Load(Long id, Result. Set rs) throws SQLException; Spring 2009 Computer Science Department, TUC-N
do. Load in Person. Mapper class Person. Mapper. . . protected Domain. Object do. Load(Long id, Result. Set rs) throws SQLException { String last. Name. Arg = rs. get. String(2); String first. Name. Arg = rs. get. String(3); int num. Dependents. Arg = rs. get. Int(4); return new Person(id, last. Name. Arg, first. Name. Arg, num. Dependents. Arg); } Spring 2009 Computer Science Department, TUC-N
Separating finders Spring 2009 Computer Science Department, TUC-N
Hybrid Data Source Patterns • Active Record = RDG + Domain Logic. • Table Module ≈ TDG + Domain Logic. – TDG like module that processes Result. Sets. Spring 2009 Computer Science Department, TUC-N
Identity Map Ensure each object only gets loaded once by keeping every loaded object in a map. Lookup objects using the map when referring to them Spring 2009 Computer Science Department, TUC-N
How it works • How many? – – One map/session One map/table One map/class One map/inheritance tree • Map key? – Primary key in the data base if it is 1 column • Explicit vs. generic – find. Person(1) – find (“Person”, 1) Spring 2009 Computer Science Department, TUC-N
Implementation private Map people = new Hash. Map(); public static void add. Person(Person arg) { sole. Instance. people. put(arg. get. ID(), arg); } public static Person get. Person(Long key) { return (Person)sole. Instance. people. get(key); } Spring 2009 Computer Science Department, TUC-N
Concurrency Patterns • Multiple processes/threads that manipulate the same data • A solution -> Transaction managers…. as long as all data manipulation is within a transaction. • What if data manipulation spans transactions? Spring 2009 Computer Science Department, TUC-N
Concurrency problems • lost updates • inconsistent read ÞCorrectness failure • liveness – how much concurrency can the system handle? Spring 2009 Computer Science Department, TUC-N
Execution contexts • “A request corresponds to a single call from the outside world which the software works on and optionally sends back a response” • “A session is a long running interaction between a client and server. ” • “A process is a, usually heavyweight, execution context that provides a lot of isolation for the internal data it works on. ” • “A thread is a lighter-weight active agent that's set up so that multiple threads can operate in a single process. ” Spring 2009 Computer Science Department, TUC-N
Solutions • isolation: partition the data so that any piece of data can only be accessed by one active agent. • immutable data: separate the data that cannot be modified. • mutable data than cannot be isolated: – Optimistic Concurrency Control – Pessimistic Concurrency Control Spring 2009 Computer Science Department, TUC-N
Optimistic Concurrency Control • • • Conflict detection Lock hold during commit Supports concurrency Low frequency of conflicts Used for not critical consequences Spring 2009 Computer Science Department, TUC-N
Pessimistic Concurrency Control • • Conflict prevention Lock hold during the entire transaction Does not suport concurrency Used for critical consequences Spring 2009 Computer Science Department, TUC-N
Preventing inconsistent reads • Optimistic control – Versioning • Pessimistic control – Read ->shared lock – Write -> exclusive lock • Temporal reads – Data+time stamps – Implies full history storage Spring 2009 Computer Science Department, TUC-N
Deadlocks • Pick a victim • Locks with deadlines • Preventing: – Force to acquire all the necessary locks at the beginning – Enforce a strategy to grant locks (ex. Alphabetical order of the files) • Combine tactics Spring 2009 Computer Science Department, TUC-N
Transactions • • • ACID Transactional resource (ex. Database) Increase throughput -> short transactions Transactions mapped on a single request Late transactions -> read data first, start transaction for updates • Transactions spanning several requests -> long transactions • Lock escalation (row level -> table level) Spring 2009 Computer Science Department, TUC-N
Application Server Concurrency • process-per-session – Uses a lot of resources • process-per-request – Pooled processes – Sequential requests – Resources for a request should be released • thread-per-request – More efficient – No isolation Spring 2009 Computer Science Department, TUC-N
Concurrency Patterns • • Optimistic Offline Lock Pessimistic Offline Lock Implicit Lock Coarse-Grained Lock Spring 2009 Computer Science Department, TUC-N
Optimistic Offline Lock Prevent conflicts between concurrent business transactions, by detecting a conflict and rolling back the transaction. Spring 2009 Computer Science Department, TUC-N
Spring 2009 Computer Science Department, TUC-N
How it works • Associate a version number to each record • When a record is loaded the session state contains the version number • Getting the lock = comparing the versions • If lock aquired -> transaction committed, version number incremented Spring 2009 Computer Science Department, TUC-N
Update optimistic check Spring 2009 Computer Science Department, TUC-N
Analysis • Versioning on UPDATE and DELETE does not prevent inconsistent reads • Add versions on items that need to be checked • does not provide adequate solutions for some of the trickier concurrency and temporal issues Spring 2009 Computer Science Department, TUC-N
Pessimistic Offline Lock Prevent conflicts between concurrent business transactions by allowing only one business transaction to access data at once. Spring 2009 Computer Science Department, TUC-N
Spring 2009 Computer Science Department, TUC-N
How it works • To implement it you need to: – know what type of locks you need, – build a lock manager, – define procedures for a business transaction to use locks • Lock types – Exclusive write lock – Exclusive read lock – Read/write lock • Read and write locks are mutually exclusive. • Concurrent read locks are acceptable Spring 2009 Computer Science Department, TUC-N
Lock manager • The lock manager's job is to grant or deny any request by a business transaction to acquire or release a lock • A table that maps locks to owners • Protocol of Business transaction to use the lock manager – what to lock, – when to release a lock, – how to act when a lock cannot be acquired. Spring 2009 Computer Science Department, TUC-N
Protocol • [when? ] acquire a lock before loading the data • [what? ] objects (id) or records (primary key) • [when to release? ] release locks when the business transaction completes • [what if acquiring fails? ] abort Spring 2009 Computer Science Department, TUC-N
Analysis • • • Access to the lock table must be serialized Performance bottleneck Consider granularity (Coarse grained lock) Possible deadlocks Lock timeout for lost sessions Spring 2009 Computer Science Department, TUC-N
Implicite lock Allow framework code to acquire offline locks Spring 2009 Computer Science Department, TUC-N
How it works • if an item might be locked anywhere it must be locked everywhere • Factor your code such that any locking mechanics that absolutely cannot be skipped can be carried out by your application framework Spring 2009 Computer Science Department, TUC-N
How it works • Optimistic lock – store a version count for each record, – include the version in update SQL criteria, – store an incremented version when changing the record • Pessimistic Lock – acquiring any lock necessary to load a piece of data – release of all locks when the business transaction or session completes – assure that a write lock has already been obtained before committing any changes Spring 2009 Computer Science Department, TUC-N
Coarse-Grained Lock a set of related objects with a single lock Spring 2009 Computer Science Department, TUC-N
How it works • create a single point of contention for locking a group of objects • Optimistic Lock –shared version Spring 2009 Computer Science Department, TUC-N
• Root lock • Navigation issues -> Lazy load Spring 2009 Computer Science Department, TUC-N
- Slides: 65