11/25/2023 0 Comments Java write a multi counter method![]() Using the AtomicInteger is equally faster and more readable than performing the same using synchronization. IsSuccess = pareAndSet(100,120) //current value 110Īs discussed above, the primary use of AtomicInteger is when we are in multi-threaded context and we need to perform atomic operations on an int value without using synchronized keyword. Import .AtomicInteger īoolean isSuccess = pareAndSet(100,110) //current value 100 We can see many real time uses of compareAndSet() method in Java concurrent collection classes such as ConcurrentHashMap. boolean compareAndSet(int expect, int update) To support compare and swap operations, this class provides a method which atomically sets the value to the given updated value if the current value = the expected value. The atomicity guarantees that the new value is calculated based on up-to-date information if the value had been updated by another thread in the meantime, the write would fail. This is done as a single atomic operation. (atomicInteger.getAndDecrement()) //105Ī compare and swap operation compares the contents of a memory location to a given value and, only if they are the same, modifies the contents of that memory location to a given new value. It is equivalent to – -i operation.ĪtomicInteger atomicInteger = new AtomicInteger(100) Immutable data is data which cannot be changed.
0 Comments
Leave a Reply. |
AuthorWrite something about yourself. No need to be fancy, just an overview. ArchivesCategories |