transaction management

Upload: yenaloca

Post on 17-Jul-2015

18 views

Category:

Documents


1 download

TRANSCRIPT

Bolivarian Republic Of Venezuela Ministry Of People's Power For University Education Polytechnic University Of The West Mariscal Sucre Caracas .-

Teacher: Martn Hernndez

Members: Lpez Miriam Exp. N: 13582945 Lpez Yenire Exp. N: 19288271 Nuez Michael Exp. N: 16086679 Computing 7121 English

May 2010 Caracas

TRANSACCIONES DEFINICIN:

Las transacciones fueron originalmente desarrolladas para ser utilizadas dentro de los sistemas de base de datos, donde se usaba para ayudar en el mantenimiento de los datos de las aplicaciones y que dependan de la consistencia de la informacin almacenada. Las transacciones son mecanismos que ayudan a simplificar la construccin de sistemas confiables mediante procesos que proporcionan soporte uniforme para invocar y sincronizar operaciones como: Operaciones de comparacin de datos Aseguramiento de la seriabilidad de las transacciones con otras Atomicidad en su comportamiento Recuperacin de fallas.

Manejo de transaccionesSe considera el manejo de transacciones cuando un dispositivo mvil inicia una transaccin hacia la base de datos o hacia un servidor fijo. La transaccin puede ejecutarse en el servidor o en el dispositivo mvil.

PROPIEDADES DE LAS TRANSACCIONESAtomicidad Una transaccin es tratada como una unidad de operacin. Por lo tanto todas las acciones de la transaccin se llevan a cabo o ninguna de ellas se realiza. La atomicidad requiere que si una transaccin se interrumpe por una falla, sus resultados parciales deben ser deshechos. Se efectan todas las transacciones, pero en caso de fallas no se realiza ninguna. Una transaccin debe concluir comprometida o abortada. En el caso del compromiso se instalan todas las actualizaciones y en el aborto se descartan todas las actualizaciones.

Consistencia

Una transaccin es un programa correcto que lleva la base de datos de un estado consistente a otro con la misma caracterstica. Gracias a esto, las transacciones no violan las reglas de integridad de una base de datos. Aislamiento Durante la ejecucin de una transaccin, esta no debe revelar sus resultados a otras transacciones concurrentes antes de su compromiso. Si varias transacciones se ejecutan concurrentemente, los resultados deben ser los mismos que si ellas se hubieran ejecutado en forma secuencial (Seriabilidad). La seriabilidad consiste en asegurarse que los cambios siguen un orden adecuado. Durabilidad Es la propiedad de las transacciones que asegura que una vez que una transaccin realiza su compromiso, sus resultados son permanentes y no pueden ser borrados de la base de datos, se asegura que los resultados de una transaccin sobrevivirn a fallas del sistema.

Estructura de las Transacciones.La estructura de una transaccin usualmente viene dada segn el modelo de la transaccin, estas pueden ser planas (simples) o anidadas. Transacciones planas:

Consisten en una secuencia de operaciones primitivas encerradas entre las palabras clave BEGIN y END. Por ejemplo: BEGIN _TRANSACTION Reservacin .... END. Transacciones Anidadas:

Consiste en tener transacciones que dependen de otras, estas transacciones estn incluidas dentro de otras de un nivel superior y se las conoce como subtransacciones. La transaccin de nivel superior puede producir hijos (subtransacciones) que hagan ms fcil la programacin del sistema y mejoras del desempeo. En las transacciones anidadas las operaciones de una transaccin pueden ser as mismo otras transacciones. Por ejemplo:

BEGIN _TRANSACTION Reservacin .......... BEGIN _TRANSACTION Vuelo ........ END.( Vuelo ) ...... BEGIN _TRANSACTION Hotel ........ END ...... END. Una transaccin anidada dentro de otra conserva las mismas propiedades que las de su padre, esto implica, que puede contener as mismo transacciones dentro de ella. Existen restricciones obvias en una transaccin anidada: debe empezar despus que su padre y debe terminar antes que el. El compromiso de una subtransaccion es condicional al compromiso de su padre, si el padre de una o varias subtransacciones aborta, las subtransacciones hijas tambin sern abortadas. Las transacciones anidadas brindan un nivel mas alto de concurrencia entre transacciones. Ya que una transaccin consiste de varias transacciones es posible tener mayor concurrencia dentro de una sola transaccin. As tambin, es posible recuperarse de de fallas de forma independiente de cada subtransaccion. Esto limita el dao a una parte mas pequea de la transaccin, haciendo que el costo de la recuperacin sea el menor.

Estados de una TransaccinActiva el estado inicial; la transaccin permanece en este estado durante su ejecucin. Parcialmente comprometida despus de ejecutarse la ltima instruccin. Fallida tras descubrir que no puede continuar la ejecucin normal. Abortada despus de haber retrocedido la transaccin y restablecido la base de datos a su estado anterior al comienzo de la transaccin. Comprometida tras completarse con xito. La ejecucin concurrente de transacciones mejora la productividad y la utilizacin del sistema, y tambin reduce el tiempo de espera de las transacciones. Reiniciar la transaccin, pero slo si la transaccin se ha abortado a causa de algn error hardware o software que no lo haya provocado la lgica interna de la transaccin. Una transaccin reiniciada se considera una nueva transaccin. Cancelar la transaccin. Normalmente se hace esto si hay algn error interno lgico que slo se puede corregir escribiendo de nuevo el programa de aplicacin, o debido a una

entrada incorrecta o debido a que no se han encontrado los datos deseados en la base de datos.

Problemas de concurrenciaEl propsito del control de concurrencia es mantener la consistencia de la BD cuando sta es actualizada por mltiples usuarios. Existen casos en los que las transacciones ejecutadas aisladamente originan nuevos estados consistentes, sin embargo las mismas transacciones ejecutadas concurrentemente pueden originar efectos como prdidas de operaciones y/o violacin de restricciones de integridad; a continuacin se ilustran algunos casos tpicos de anomalas.

Planificacin de Transacciones: Representan el orden cronolgico en el que se ejecutan las instrucciones de diferentes transacciones concurrentes. Cualquier planificacin vlida debe constar de todas las instrucciones de la transaccin y en el mismo orden. Ej:

Ti Leer(A)

Tj Leer (B) Escribir (B) Escribir(C) Leer(C)

Planificacin Secuencial: se produce cuando las instrucciones de cada transaccin estn juntas y solo inician cuando terminan las de la transaccin anterior. Ej.:

Ti Leer(A) Escribir (B) Leer(C)

Tj

Leer (B) Escribir(C)

Ti

Tj Leer (B) Escribir (C)

Leer (A) Escribir (B) Leer (C)

ConcurrenciaEn computacin, la concurrencia es la propiedad de los sistemas que permiten que mltiples procesos sean ejecutados al mismo tiempo, y que potencialmente puedan interactuar entre s. Los procesos concurrentes pueden ser ejecutados realmente de forma simultnea, slo cuando cada uno es ejecutado en diferentes procesadores. En cambio, la concurrencia es simulada si slo existe un procesador encargado de ejecutar los procesos concurrentes, simulando la concurrencia, ocupndose de forma alternada en uno y otro proceso a pequesimos intervalos de tiempo. De esta manera simula que se estn ejecutando a la vez.

Conflictos en la concurrencia

En los sistemas de tiempo compartido (aquellos con varios usuarios, procesos, tareas, trabajos que reparten el uso de CPU entre estos) se presentan muchos conflictos debido a que los procesos compiten por los recursos del sistema. Los programas concurrentes a diferencia de los programas secuenciales tienen una serie de conflictos muy particulares derivados de las caractersticas de la concurrencia: Violacin de la exclusin mutua: En ocasiones ciertas acciones que se realizan en un programa concurrente no proporcionan los resultados deseados. Esto se debe a que existe una parte del programa donde se realizan dichas acciones que constituye una regin critica, es decir, es una parte del programa en la que se debe garantizar que si un proceso accede a la misma, ningn otro podr acceder. Se necesita pues garantizar la exclusin mutua. Bloqueo mutuo o deadlock: Un proceso se encuentra en estado de deadlock si esta esperando por un suceso que no ocurrir nunca. Se puede producir en la comunicacin de procesos y mas frecuentemente en la gestin de recursos.

CorrectitudEn teora de la computacin, la correccin de un algoritmo, tambin llamada correctitud (como adaptacin de la palabra inglesa correctnes), corresponde a una propiedad que distingue a un algoritmo de un procedimiento efectivo. Un algoritmo es correcto, si: 1. 2. 3. Resuelve el problema computacional para el cual fue diseado. Para cada entrada, produce la salida deseada. Termina en un tiempo de ejecucin finito.

Si cualquiera de estos tres puntos no se cumple, entonces estamos hablando de un algoritmo incorrecto, que para efectos prcticos, carece de utilidad, al no ser ms que un procedimiento efectivo, es decir, una secuencia ordenada y determinista de pasos.

SeriabilidadConsiste en asegurarse que los cambios siguen un orden adecuado. Con el fin de garantizar la seriabilidad de las transacciones se recomienda:

Asignar un orden a los items a bloquear y requerir que todas las transacciones efecten los bloqueos respetando el orden.

Requerir que en una transaccin todos los bloqueos precedan a todos los desbloqueos (teorema de ejecucin en dos fases).

Algoritmos de control de concurrencia: Los algoritmos de control de concurrencia deben sincronizar la ejecucin de transacciones concurrentes bajo el criterio de correctitud. La consistencia entre transacciones se garantiza mediante el aislamiento de las mismas. Los algoritmos pesimistas sincronizan la ejecucin concurrente de las transacciones en su etapa inicial de su ciclo de ejecucin. El grupo de algoritmos pesimistas consiste de algoritmos basados en candados, algoritmos basados en ordenamiento por estampas de tiempo y algoritmos hbridos.

Los algoritmos optimistas retrasan la sincronizacin de las transacciones hasta su terminacin. El grupo de los algoritmos optimistas se clasifican por basados en candados y basados en estampas de tiempo.

Algoritmo de bloqueo

Tambin reciben el nombre de candado. En realidad, un bloqueo es una variable asociada con un tem de la Base de Datos; utilizada para almacenar el estado de ese tem con respecto a posibles operaciones que le puedan ser aplicadas. Usamos los bloqueos como un medio de sincronizar los accesos de transacciones concurrentes a los items de la Base de Datos.

ENGLISH

TRANSACTIONS DEFINITIONThe transactions were originally developed for use within the database systems, where it was used to assist in maintaining data and applications that depended on the consistency of the stored information. Transactions are mechanisms that help simplify the construction of reliable systems through processes that provide uniform support for invoke and synchronize operations as:

Operations Data Comparison Ensuring the serializability of transactions with other Atomicity in behavior Failover

Transaction ManagementIt considers the management of transactions when a mobile device initiates a transaction to the database or to a fixed server. The transaction can be executed on the server or mobile device.

PROPERTIES OF TRANSACTIONS Atomicity A transaction is treated as a unit operation. Thus all actions of the transaction are performed or none of them is performed. Atomicity requires that if a transaction is interrupted by a failure, its partial results must be undone. All transactions are made, but in case of failures do not perform. A transaction must conclude committed or aborted. In the case of commitment all updates are installed on abortion and all updates are discarded. Consistency A transaction is a correct program that takes the database from a consistent state to another with the same characteristic. Because of this, transactions do not violate the rules of integrity of a database. Isolation During the execution of a transaction, it should not reveal their results to other concurrent transactions before its commitment. If several transactions are executed concurrently, the results should be the same as if they had been executed sequentially (serializability). Serializability is to ensure that the changes follow a proper order. Durability It is the property of transactions ensures that once a transaction completes its commitment, its results are permanent and can not be deleted from the database, ensure that the results of a transaction survive system failures.

Transaction StructureThe structure of a transaction usually is given on the model of the transaction, they can be flat (simple) or nested. Transactions flat: Consist of a sequence of primitive operations enclosed between the keywords BEGIN y END. Por ejemplo: BEGIN _TRANSACTION Reservacin .... END. Nested Transactions:

It contains a dependent on other transactions; these transactions are included within other higher-level and are referred to as subtransactions. The top-level transaction can produce children (subtransactions) to make programming easier and improved system performance. Nested transactions in the operations of a transaction can be likewise other transactions. For example: BEGIN _TRANSACTION Reservacin .......... BEGIN _TRANSACTION Vuelo ........ END.( Vuelo ) ...... BEGIN _TRANSACTION Hotel ........ END ...... END.

A nested inside another transaction retains the same properties as those of his father, this implies that it may contain and transactions within it. There are obvious restrictions in a nested transaction: should start after his father and must end before that. The commitment of subtransactions is conditional upon the commitment of his father if the father of one or more subtransactions aborts, the daughters will also be aborted subtransactions. Nested transactions offer a higher level of concurrency between transactions. Since a transaction consists of several transactions may be more competition within a single transaction. Also, you can recover from failure independently of each subtransactions. This limits the damage to a smaller part of the transaction, making the cost of recovery is less.

Transaction StatusEnables: the initial state, the transaction remains in this state for its implementation. Partially committed after executing the last instruction. Failed: after discovering they can not continue normal execution. Aborted: receded after the transaction and the database restored to its previous state at the beginning of the transaction. Committed after a successful completion.

The concurrent execution of transactions improves productivity and system utilization, and also reduces the waiting time of transactions Restart the transaction, but only if the transaction has been aborted because of some hardware or software error that has not caused the internal logic of the transaction. A restarted transaction is considered a new transaction. Cancel the transaction. Usually done that if there is a logical internal error can be corrected only rewriting the application program, or because of an incorrect entry or because they have not found the desired data into the database.

Concurrency ProblemsThe purpose of concurrency control is to maintain the consistency of the database when it is updated by multiple users. There are cases in which transactions executed in isolation rise to new states consistent, however the same transactions executed concurrently can cause effects such as loss from operations and / or violation of integrity constraints, and then illustrates some typical cases of anomalies.

TransactionREAD executed

Transaction

Transaction

Transaction

Transaction Planning: They represent the chronological order in which instructions are in different concurrent transactions. AnyREAD valid planning should include all PRINT READ instructions of the transaction and in the same order. ExampleREAD WRITE

Ti Read (B)

TjREAD PRINT

WRITE

WRITE

Read (A)Operating loss

Write (B) Write(C) Read (C)

Not reproduction of readings

Transaction

Transaction

Transaction

Transaction

Sequential Planning: This occurs when the instructions for each transaction are started together and only when they finish the previous transaction. Example: READ READWRITE

TiREAD PRINT Read (A) READ Write (B) PRINT

Tj

WRITE READ WRITE READ

READ WRITE

Read (C)

Read (B)

WRITE READ WRITE

Inconsistent output

Introduction of inconsistencies in the BD

Write(C)

Ti

Tj Read (B) Write (C)

Read (A) Write (B) Read (C)

ConcurrenceIn computing, concurrency is a property of systems that allow multiple processes to be executed at the same time, and that potentially interact with each other. Concurrent processes can be executed simultaneously really, only when each is run on different processors. Instead, concurrency is simulated if only one processor responsible for executing concurrent processes, simulating the crowd, seized alternately in either process very small time intervals. In this way simulates that are running at once.

Conflicts in the concurrenceIn time-sharing systems (those with multiple users, processes, jobs, jobs that share the CPU utilization between these) presents many conflicts because the processes are competing for system resources. Concurrent programs unlike sequential programs have a very specific series of conflicts resulting from the characteristics of the concurrence: Violation of mutual exclusion: Sometimes certain actions that are performed in a concurrent program does not provide the desired results. This is because there is a part of the program where such actions are performed is a critical region, ie is a part of the program in which we must guarantee that if a process accesses the same, no one else can access. Is therefore required to ensure mutual exclusion. Deadlock or deadlock: A process is in a state of deadlock if it is waiting for an event that will never happen. May occur in the communication process and more frequently in resource management.

Correctness

In theory of computation, the correction of an algorithm, also called correctness (as an adaptation of the English word correctnes) corresponds to a property that distinguishes an algorithm of an effective procedure.

An algorithm is correct if: 1. Solves the computational problem for which it was designed. 2. For each entry, produces the desired output. 3. Ends in a finite run time. If any of these three points are not met, then we are talking about a wrong algorithm, which for practical purposes, useless, to be nothing more than an effective procedure, ie an orderly sequence of steps.

SerializabilityIs to ensure that the changes follow a proper order. In order to ensure serializability of transactions is recommended: Assign an order to block items and require that all transactions carried out in compliance with the order blocks. Require that a transaction all locks precede all unlocks (theorem implemented in two phases). Concurrency control algorithms: The concurrency control algorithms to synchronize concurrent execution of transactions under the criterion of correctness. The consistency between transactions is ensured by isolating them. Pessimistic algorithms synchronize the concurrent execution of transactions in its initial stage of its implementation cycle. The pessimistic group of algorithms consists of algorithms based on locks, computer-based algorithms for time stamps and hybrid algorithms.

Optimistic algorithms delay the timing of the transaction to completion. The groups of optimistic algorithms are classified based on locks and based on time stamps.

Locking algorithm.

They are known to lock. In fact, a lockout is a variable associated with an item from the database, used to store the state of that item with respect to possible operations that may

be applied. We use locks as a means to synchronize concurrent access to transaction items in the database.

Concurrency Control Algorithms

Pessimistic

Optimistic

padlocks

Timestamps

Hybrids

padlocks

Timestamps

centralized

Basic

primary copy

Multi version

distributed

Conservatives