Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java: Rollback Codes

Tags:

java

rollback

Is there any workaround that can rollback codes in Java?

For example I want the code below prints out i = 1 but not 2: (When an exception occurs)

int i = 1;
try {
    i = 2;
    int j = 10/0;
} catch (Exception ex) {}
System.out.print("i = " + i);

I don't think this logic is practically useless for programmers. And I don't think this is very hard to handle for the compiler.

For instance, it could temporary saved i = 1 in the memory and after an exception occurred, rolled back it's value to 1 instead of 2. (It would be better if we had rollback/catch for example)

like image 907
Vahid Avatar asked Nov 08 '12 07:11

Vahid


People also ask

What is the rollback command?

The ROLLBACK command is the transactional command used to undo transactions that have not already been saved to the database. This command can only be used to undo transactions since the last COMMIT or ROLLBACK command was issued.

Can we rollback the transaction in JDBC?

Thus, since rollback() undoes any changes in the current transaction (as per the javadoc), it will effectively do nothing.


2 Answers

How about this?

    int i = 1;
    int oldValue = 0;
    try {
        oldValue = i;
        i = 2;
        int j = 10 / 0;
    } catch (Exception ex) {
        i = oldValue;
    }
    System.out.print("i = " + i);
like image 185
Mawia Avatar answered Oct 13 '22 01:10

Mawia


Essentially, you need to version your memory. This has been explored in several research, such as transactional memory, object-graph versioning, object database.

The problem is that it's harder to do correctly than it seems like. Typical non-trivial issues to handle are:

  • How much do you version? The whole reachable object graph? A subset of interest?
  • What about the interaction between versioned and non-versioned data structured?
  • What about other operations that can happen within the "recoverable block" like spawning threads, and reading/writing IO. Do you want to undo that? Can you?

Transactional memory is slowely becoming a mainstream mechanism, with language like Clojure. It requries however a special kind of design to deal with the above issues. Clojure achieves a nice balance since it is essentially functional, and versioned data are explicitely identified. Adding similar features to an object-oriented imperative language like Java doesn't come for free.


You might be interested in the following links/publications:

like image 43
ewernli Avatar answered Oct 13 '22 02:10

ewernli