MYISAM Locking Explained

Why Table Locking Occurs in MyISAM

Locks exist, in a nutshell, to prevent queries from altering data while that data is being read by another process. Or vice-versa.
There are different types of locking in the database world. MyISAM happens to use table locks which are very fast. They are easier to implement when compared to the row-level locking employed by InnoDB and permit a higher query throughput. That assumes of course the number of writes that occur on your database is few. Or, and this is sometimes overlooked, that no one query takes more than an instant.
After all it's the being locked out that hurts — writes tend to go through pretty quickly — but if they have to wait for a query to complete...

Imagine The Scenario

  1. 0.00 seconds A select query (ie. read-only) accesses the table, it will take around 2 seconds to complete.
  2. 0.01 seconds Another select query accesses the table, it takes no time and will complete in an instant as it can run in parallel.
  3. 0.02 seconds An insert, delete or update query (ie. write) attempts to write to that very same table before the first select has completed.
  4. 0.03 seconds A select query comes in, again waiting for the first select to complete.
  5. 0.04 seconds Another select query comes in, again waiting for the first select to complete.
  6. 0.05 seconds Yet another select query comes in, again waiting for the first select to complete.
  7. 1.99 seconds (~1000 queries later) Yet another select query comes in, again waiting for the first select to complete.
And so on and so forth. The queries in orange and red are blocked and have to wait for the first select to complete before they can be executed. The selects in red are blocked by the write operation in orange which is in turn blocked by the long-running select in green. This is what causes the table_locks_waited value to grow.
See what happens if you've a query that takes any more than an instant and another query comes along, needing to write to the table? A whopping great long queue that's what. And therefore a collapse in parallelism. You're not going to scale like this.
What the above does not tell you is that a table 'insert' can occur whilst a select query has a read lock on a table providing all empty space within a table has been filled and it is therefore appending to the end of the table.  If there is a gap in the table it will attempt to fill those gaps first and will queue the write after the running select (write lock will get a higher priority than a queued read lock and run before the read locks).  If the insert is at the end of the table then it can occur whilst the select statement is running with a read lock.

Comments

Popular posts from this blog

SQL SERVER – Event ID 107- Report Server Windows Service (MSSQLSERVER) cannot connect to the report server database.

SQL Server Builds Information

Using DBCA silent install and disabling automatic memory management