Java 8 FindFirst() | What is AtomicInteger() | Find First Non Consecutive Number Demo | InterviewDOT

preview_player
Показать описание

Stream findFirst() in Java with examples
Stream findFirst() returns an Optional (a container object which may or may not contain a non-null value) describing the first element of this stream, or an empty Optional if the stream is empty. If the stream has no encounter order, then any element may be returned.

Java 8 FindFirst() | What is AtomicInteger() | Find First Non Consecutive Number Demo | InterviewDOT

AtomicInteger is a class specially designed to update integers in a thread-safe way. Why do we need this a class? Why can we not simply use a volatile int? And how can we use AtomicInteger?

How to Use AtomicInteger
The class AtomicInteger has multiple methods that allow us to update the AtomicInteger atomically. For example, the method incrementAndGet atomically increments the AtomicInteger and decrementAndGet decrements the AtomicInteger.

But the method compareAndSet is special. This method allows us to implement arbitrary calculations atomically. The compareAndSet method takes two parameters, the expected current value, and the new value. The method atomically checks if the current value equals the expected value. If yes, the method updates the value to the new value and return true. If not, the method leaves the current value unchanged and returns false.

The idea to use this method is to let compareAndSet check if the current value was changed by another thread while we calculated the new value. If not we can safely update the current value. Otherwise, we need to recalculate the new value with the changed current value.

AtomicInteger lets us update integers in a thread-safe way. Use atomic methods like incrementAndGet or decrementAndGet for simple types of calculations. And use the methods get and compareAndSet for all other types of calculations.

Рекомендации по теме
Комментарии
Автор

Great video sir. With a very good explanation . Keep up the great work. 👌👌✌

saiprakash
join shbcf.ru