Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Thread-safe code without using the `synchronized` keyword?

What are the possible ways to make code thread-safe without using the synchronized keyword?

like image 493
chhaya Avatar asked Apr 26 '12 09:04

chhaya


2 Answers

Actually, lots of ways:

  1. No need for synchronization at all if you don't have mutable state.
  2. No need for synchronization if the mutable state is confined to a single thread. This can be done by using local variables or java.lang.ThreadLocal.
  3. You can also use built-in synchronizers. java.util.concurrent.locks.ReentrantLock has the same functionality as the lock you access when using synchronized blocks and methods, and it is even more powerful.
like image 156
Malcolm Avatar answered Sep 21 '22 15:09

Malcolm


Only have variables/references local to methods. Or ensure that any instance variables are immutable.

like image 31
NimChimpsky Avatar answered Sep 18 '22 15:09

NimChimpsky