How to explain atomic actions?

2019-04-11 19:49发布

问题:

What are atomic actions and why they are neccessary? Also, How are atomic actions implemented in Java?

My understanding is that in programming an atomic action is one that effectively happens all at one. An atomic action cannot stop in the middle it either happens completely or not at all.

For example, ordering an airline ticket online where two actions are required: payment and a seat reservation. The potential passenger must either.

  1. both pay and reserve a seat, OR
  2. neither pay nor reserve a seat

回答1:

Maybe you should think about transactions. Make some process but do not save changes until everything is in order. Like when you are withdrawing money from a machine, you follow a series of steps, before seeing changes on your account, i.e. Put your card, your password, say how much money you want, receive the money. If something fails in one of the steps, you dont see changes in your savings account, e.g. your password was incorrect, or you are trying to withdraw more money than what you have...

You can read the java tutorial. http://docs.oracle.com/javase/tutorial/essential/concurrency/atomic.html



回答2:

Your explanation, IMHO, rather explains what atomicity means regarding database transactions: the A in ACID.

Regarding concurrency, atomicity rather means that when a thread modifies the state of some object (or set of objects), another thread can't see any intermediary state. Either it sees the state as it was before the operation, or it sees the state as it is after the operation.

For example, changing the value of a long variable is not an atomic operation. It involves setting the value of the 32 first bits, and then setting the state of the 32 last bits. If the access to the long variable is not properly synchronized, a thread might see the intermediary state: the 32 first bits have been changed, but the 32 last bits haven't been changed yet.

The way to implement atomic operations is to use synchronization. synchronization involves using

  • the synchronized keyword
  • the volatile keyword
  • atomic variables (AtomicInteger, etc.)


回答3:

well, is not that an atomic action cannot be stopped in the middle. Is more: all his effects become visible when the action is completed (commit) or are not visible at all (abort/rollback); so it can be stopped, but the state of the system is not updated.



回答4:

By reading the Java tutorial on Atomic Access



回答5:

Atomicity - means in a transaction either all statements are executed or none of them are executed.

If a transaction has 5 statements. If a failure occurs before all the statements are run, then atomicity means that either 5 statements are executed OR none of them are executed.