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)
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.
Thus, since rollback() undoes any changes in the current transaction (as per the javadoc), it will effectively do nothing.
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);
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:
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:
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With