• Home
  • Chemistry
  • Astronomy
  • Energy
  • Nature
  • Biology
  • Physics
  • Electronics
  • Understanding Atomic Scope in Programming: Ruby & JavaScript
    In programming, atomicity describes the indivisibility of an operation; that is, either all of the operation is completed, or none of it. In some programming languages, notably Ruby and JavaScript, atomicity is referred to as an *atomic scope*.

    To understand atomicity and atomic scopes, consider the following, non-atomic, sequence of operations to modify a user's bank balance:

    1. Read the balance from the bank.

    2. Subtract the transaction amount from the balance.

    3. Write the balance back to the bank.

    For these operations to succeed, the database needs to be locked between the read and the write, because otherwise another transaction may write to the database between these two operations. Furthermore, if anything goes wrong during the transaction (e.g., the database goes offline during the write operation), the operation must fail completely, and the database must be restored to the state that it was in before the transaction started.

    With atomicity, the series of operations behaves as a single operation, or it fails entirely. That is, the code to perform a given operation is enclosed within an *atomic scope*, and if any operation in the sequence fails, the entire transaction is rolled back, as though none of the operations in the sequence had ever occurred.

    An atomic scope guarantees:

    1. If no operation in the scope fails, all of the operations occur;

    2. If any operation in the scope fails, none of the operations occur; and

    3. If any operation begins to fail, any operations that have already occurred are immediately rolled back, restoring the system to its state before any of the operations began.

    Science Discoveries © www.scienceaq.com