Featured post
java - if multiple threads are updating the same variable, what should be done so each thread updates the variable correctly? -
if multiple threads updating same variable, should each thread updates variable correctly?
any appreciated
there several options:
1) using no synchronization @ all
this can work if data of primitive type (not long/double), , don't care reading stale values (which unlikely)
2) declaring field volatile
this guarantee stale values never read. works fine objects (assuming objects aren't changed after creation), because of happens-before guarantees of volatile variables (see "java memory model").
3) using java.util.concurrent.atomiclong, atomicinteger etc
they thread safe, , support special operations atomic incrementation , atomic compare-and-set operations.
4) protecting reads , writes same lock
this approach provides mutual exclusion, allows defining large atomic operation, multiple data members manipulated single operation.
- Get link
- X
- Other Apps
Comments
Post a Comment