0

Atomicity from the A in ACID properties for database transactions tells that each transaction conducted on a database is like binary number system, 0 or 1, all or nothing.

Is it possible to achieve the same in programming languages like Java or C# or any other general purpose language? e.g.

public static Ticket GetTicket(string filePath) {
  counter++;
  Application app = new Application(filePath);
  .
  .
  .

Probably, I am giving a bad example, but I believe this should be enough to give an idea. Now, imagine if the line where I am creating an Application object throws an exception, then the execution of the application would halt and the state of the static variable counter will already have been mutated and the state of the system changed. Is there a way to prevent the damage being done by statements executed before an exception is thrown?

Nikit Batale
  • 1,790
  • 2
  • 15
  • 20

4 Answers4

5

You are thinking of software transactional memory, which has library implementations in Java and C#

Zim-Zam O'Pootertoot
  • 17,888
  • 4
  • 41
  • 69
1

The simplest mechanism for such a feature would be to:

  1. clone the object that would be mutated by statements following
  2. mutate the cloned object
  3. update the reference to point to the cloned object

That way, no changes in a reference to an object are actually observed until the final step.

Without a more specific question however, this would be difficult to answer correctly.

Karl Harnagy
  • 717
  • 5
  • 10
0

Save all of your statuses before shooting the event in some variables and etc. Then do the changes in a try catch structure. in cache then roll back all of the changes into its original status

int a = 5;
int b = 1;

int a2 = a;
int b2 = b;

try
{
 a += 10;
 b -= 1;
 a /= b;
}
catch(Exception ex)
{
 //roll back;
 a = a2;
 b = b2;
}
Armen
  • 1,083
  • 2
  • 10
  • 18
0

Encapsulate all your mutable state in an immutable object.

An immutable object ideally contains only (private) readonly fields encapsulated by public getter properties. All the fields must be initialised with data passed to a constructor (or static factory method).

If you use such an immutable object, you are guaranteed that the state cannot be partially updated (other than via reflection) which gives you transactional semantics.

Anything which wishes to change part of the state must construct and return a new instance of the immutable object with all its state set appropriately.

(You can also use an immutable interface to represent an immutable object, but it is harder to guarantee that an object referenced via an interface won't be mutated since the instance might really be a mutable object.)

Matthew Watson
  • 104,400
  • 10
  • 158
  • 276