Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a way to ensure some statements are executed in atomic way

Tags:

java

Having some line of statements, is there a simple way to assure it is executed in atomic way?

like image 314
user496949 Avatar asked Apr 13 '11 05:04

user496949


2 Answers

Atomic? No. Despite what people are saying here, thread-safe doesn't mean atomic:

// this is NOT atomic!
synchronized(this) {
    makeChangeA();
    makeChangeB();
}

if makeChangeB() throws an exception, makeChangeA() will not rollback it's change.

Definition of atomic is "executed either completely, or not at all". Synchronized block is not atomic.

like image 128
Vladimir Dyuzhev Avatar answered Sep 19 '22 07:09

Vladimir Dyuzhev


If your emphasis is on "simple way", you can try out the @Synchronized annotation of Project Lombok.

like image 40
bdhar Avatar answered Sep 21 '22 07:09

bdhar