Compare and Swap in Java

  Рет қаралды 15,337

Jakob Jenkov

Jakob Jenkov

Күн бұрын

Compare and swap is an alternative to Java synchronized blocks when designing concurrent data structures or algorithms. A compare and swap operation first compares the value of a variable with an expected value, and if the values are equal, swaps the value of the variable with a new value. Compare and swap is abbreviated CAS. A compare and swap operation is atomic.
Compare and swap is especially useful for check-then-act type code. You can use compare and swap operations to guard a critical section, or for optimisticl locking style concurrency.
Chapters:
0:00 Compare and swap introduction
0:31 Compare and swap example
1:45 Compare and swap for check-then-act cases
5:45 Compare and swap used in a lock implementation
9:32 Compare and swap vs. Java synchronized blocks
17:59 Compare and swap as guard for critical section
18:59 Compare and swap for optimistic locking
Compare and swap tutorial - text:
tutorials.jenkov.com/java-conc...
Java Concurrency tutorial - text / video:
tutorials.jenkov.com/java-conc...
• Java Concurrency and M...

Пікірлер: 53
@klausdupont6335
@klausdupont6335 3 жыл бұрын
The illustrations and code examples are not only simple enough for a newcome to understand but also complicated enough to demonstrate use cases. Thanks for the concurrency series!
@JakobJenkov
@JakobJenkov 3 жыл бұрын
Thanks - I am happy to hear that! :-)
@brianstuart1126
@brianstuart1126 3 жыл бұрын
Your concurrency playlist is the simply the most clear explanation on whole KZbin. Please continue with more videos on Java Concurrency.
@JakobJenkov
@JakobJenkov 3 жыл бұрын
Thank you :-) ... I have covered most of the basics by now. There are still some advanced topics to cover. I will see when I get the time for them :-)
@volodymyrkomliev5849
@volodymyrkomliev5849 3 ай бұрын
This explanation is brilliant! All these Java Concurrency and Multithreading are amazing! I think every can understand your explanation. Thank you, Jakob, for this useful tutorial. Never be too late to understand Java threads. 🙂
@JakobJenkov
@JakobJenkov 2 ай бұрын
Great to hear! !! :-)
@ShekharKumar-sg3gd
@ShekharKumar-sg3gd Ай бұрын
I have read Java Threads 2 book and I can say that this series is not less than that complete book. Its illustration and explanation is excellent.
@JakobJenkov
@JakobJenkov Ай бұрын
Thank you very much!! :-)
@susantc5288
@susantc5288 2 жыл бұрын
I am so grateful that you take the time to do these videos. You had stopped for awhile and now you are back. Thank you so much. You are much appreciated!
@JakobJenkov
@JakobJenkov 2 жыл бұрын
Thank you very much! I am happy my videos are useful for you! :-) I will keep making videos from time to time, but I don't have as much time for it as I had earlier.
@ggsgetafaf1167
@ggsgetafaf1167 2 ай бұрын
thank you, I appreciate your video ❤
@JakobJenkov
@JakobJenkov 2 ай бұрын
You are welcome 😊
@krellin
@krellin 3 жыл бұрын
CAS is the magic that allows you to write non blocking awesomeness )
@JakobJenkov
@JakobJenkov 3 жыл бұрын
Yup :-) ... by the way, I am working on some principles for single-threaded concurrency - meaning making progress on multiple tasks from within a single thread. While non-blocking concurrency is great, no thread problems is even greater :-D ... You can probably not avoid having some level of thread communication - but it can be reduced quite a lot!
@krellin
@krellin 3 жыл бұрын
while i think its a must for any respectable programmer to know how and be able to code using different concurrency approaches... in real production code i do not let people mess with threads, kotlin with coroutines pretty much solved general purpose concurrency for jvm once and for all with the correct way... it is amazing what you can do with a good compiler.. why java compiler devs didn't do it is beyond me, so many issues/bugs could be avoided
@akcgupta
@akcgupta 3 жыл бұрын
Very nice explanation and quite interesting to know the internals of JAVA controls used for concurrency and asynchronity
@JakobJenkov
@JakobJenkov 3 жыл бұрын
Thanks ! :-)
@ultrablack7271
@ultrablack7271 3 жыл бұрын
Very interesting, thank you!
@JakobJenkov
@JakobJenkov 3 жыл бұрын
You are welcome! Glad you liked it! :-)
@kafychannel
@kafychannel Жыл бұрын
Finally I grasp how getAndIncrement() works! And how atomic variables make their operations to be atomically. Thank you so much !!!
@JakobJenkov
@JakobJenkov Жыл бұрын
Great! You are welcome! :-)
@AlexeySilichenko
@AlexeySilichenko 10 ай бұрын
Thank you very much! Great explanation 🙂
@JakobJenkov
@JakobJenkov 10 ай бұрын
You are welcome ! 😊
@andrewshatnyy
@andrewshatnyy 2 жыл бұрын
Pure gold!
@JakobJenkov
@JakobJenkov 2 жыл бұрын
Thanks! :-)
@TheGuroguro12
@TheGuroguro12 Жыл бұрын
thank you!
@JakobJenkov
@JakobJenkov Жыл бұрын
You are welcome! :-)
@smitmandavia5044
@smitmandavia5044 4 ай бұрын
Thanks for the video! Now that we have virtual threads, do you think they would be using something similar to compare and set lock? Or even locks in virtual threads are expensive than compare and set lock? (If not, why not do so?)
@JakobJenkov
@JakobJenkov 4 ай бұрын
Virtual threads are not lighter than platform threads when it comes to locking. It's the same underlying mechanism as far as I understand. The only difference is, that virtual thread that is blocked can be "detached" from the platform thread executing it, and the platform thread can then execute another virtual thread.
@ggir9979
@ggir9979 2 жыл бұрын
The AtomicBoolean class uses the new (since Java 9) varHandle class for performing the compareAndSet natively. Could you make a video on varHandle and the Unsafe package? It's got so much goodies in it for advanced java programming, but it's been hard to find a good tutorial.
@JakobJenkov
@JakobJenkov 2 жыл бұрын
The Unsafe package - is that not being removed or at least restricted in later versions of Java?
@LucAlucard1
@LucAlucard1 5 ай бұрын
Professor, thanks for this explanation! One question, should we always use `.compareAndSet` method from any Athomic data structure to deal with multi-threads? I'm asking that because I've seem multiple codes using `AtomicLong`, `AtomicInt`, `AtomicWhatever`, only like `atomicLong = atomicLong + 1`. If I understood correctly, use it like that may lead to the same issues as an usual `Long`. Is my understanding correct?
@JakobJenkov
@JakobJenkov 5 ай бұрын
You should always update the state of the _same_ AtomixXYZ instance using its methods. It can be set(), compareAndSet() or whatever else method you need in the given situation.
@LucAlucard1
@LucAlucard1 5 ай бұрын
@@JakobJenkov thanks for explaining, Jakob! Your playlist is just brilliant
@kaimingyang4140
@kaimingyang4140 27 күн бұрын
My understanding is: Java threads are all user-level, and there is no need to trap to OS level for context switching. But what you said about Synchronized relies on JVM or OS to keep synchronization. I don’t quite understand the part about (implementation of) Synchronized. Can you recommend some reading materials or make a series of videos to explain JVM in depth?
@JakobJenkov
@JakobJenkov 27 күн бұрын
As far as I know, the threads in Java are OS threads. It is the new Virtual Threads that are user level.
@kaimingyang4140
@kaimingyang4140 27 күн бұрын
@@JakobJenkov thx for your reply, your videos are really really really good~~
@andreytokarskiy9901
@andreytokarskiy9901 Жыл бұрын
In the first picture, it says that if NO, then keep old value 34. But since it is NO, it is not 34 any more. So, it should just say, keep old value of var whatever it is. Thank you
@sumitkumarmahto5081
@sumitkumarmahto5081 3 жыл бұрын
Hi Jakob, I had a doubt here, in the 1st scenario what causes that delay(wasted time by thread 1) even after the thread 2 has left the synchronized block?
@JakobJenkov
@JakobJenkov 3 жыл бұрын
Just the time it takes before the OS decides to unblock the thread again that is waiting to enter the synchronized block
@MrFireflies749
@MrFireflies749 2 жыл бұрын
Hi as you said that atomic operator compareAndSwap only run for 1 thread because CPU and chipset. Why don't we define an atomic operator called : increase(int delta). In this operator we get the volatile original value then originalValue+=delta. So we don't need to compare and resolve ABA problem.
@MrFireflies749
@MrFireflies749 2 жыл бұрын
Could you please clarify it?
@JakobJenkov
@JakobJenkov 2 жыл бұрын
The AtomicLong class has methods for incrementing and adding atomically, as far as I remember. But this video is about the compare and swap technique in general, so I focused on yhe features related to that.
@9714
@9714 Жыл бұрын
how about LongAdder and LongAccumulator ?
@chitthiaayeehai
@chitthiaayeehai 2 жыл бұрын
Dude u r just amazing 👏 Could u pls help with some kubernetes n cloud related stuff
@JakobJenkov
@JakobJenkov 2 жыл бұрын
Hi Debashis, thanks! I don't know enough about Kubernetes to make videos about it, unfortunately. But TechWorld With Nana (YT channel) has some videos about both Kubernets and Docker: kzbin.info/door/dngmbVKX1Tgre699-XLlUA
@chitthiaayeehai
@chitthiaayeehai 2 жыл бұрын
@@JakobJenkov thanks a lot 👍
@akashagarwal6390
@akashagarwal6390 Жыл бұрын
compareAndSet() vs set() diff?
@JakobJenkov
@JakobJenkov Жыл бұрын
compareAndSet() only sets the value if the value compared to is equal to the value before the "set" of the new value. Otherwise it will not set a new value.
@croydon21H
@croydon21H 2 жыл бұрын
I am unable to relate this to real world scenario , lets say a bank. what is the use case? add 1 is a literal and understand it can be 34 or 83, but it still is a literal.
@JakobJenkov
@JakobJenkov 2 жыл бұрын
Compare and swap is usually used when you need high performance (low latency) thread communication. In a bank that would happen inside the bank's database. You might not see it in your own code. In Java code it might be used e.g. in a custom queue implementation such as the LMAX disrupter or some of the concurrent queues in the JC Tools open source project. I am not saying that these tools use compare and swap - but they could.
@aleksandrkravtsov8727
@aleksandrkravtsov8727 10 ай бұрын
Is it correct that CAS and Monitor can be replaced with each other in every use case or there are use cases when Monitor can't do what CAS can and vice versa?
@JakobJenkov
@JakobJenkov 10 ай бұрын
A monitor object in Java requires a synchronized block a is as such a blocking operation. As far as I understand, a CAS is atomic but not blocking. You could use CAS to implement a monitor / mutex in Java, and probably also use a monitor / synchronized block to implement CAS. Also, since CAS is not blocking, you could use CAS to implement an optimistic locking style of guarding code around a critical section - to avoid blocking a thread.
False Sharing in Java
17:33
Jakob Jenkov
Рет қаралды 11 М.
Java Lock
28:51
Jakob Jenkov
Рет қаралды 43 М.
🍕Пиццерия FNAF в реальной жизни #shorts
00:41
Cute Barbie Gadget 🥰 #gadgets
01:00
FLIP FLOP Hacks
Рет қаралды 42 МЛН
Super gymnastics 😍🫣
00:15
Lexa_Merin
Рет қаралды 81 МЛН
k-mer algorithms: Compare and Swap
5:15
RobEdwards
Рет қаралды 16 М.
Java Threads - Creating, starting and stopping threads in Java
17:14
The Java Memory Model - The Basics
23:41
Jakob Jenkov
Рет қаралды 118 М.
Java ExecutorService - Part 1
20:55
Jakob Jenkov
Рет қаралды 51 М.
Phaser vs CountDownLatch vs CyclicBarrier
13:40
Defog Tech
Рет қаралды 75 М.
Java Concurrecy: Volatile vs Atomic - Java Programming
10:50
Will Tollefson
Рет қаралды 1,7 М.
Producer Consumer Pattern - With Java Example
19:50
Jakob Jenkov
Рет қаралды 26 М.
Java ThreadLocal
14:36
Jakob Jenkov
Рет қаралды 34 М.
Apple watch hidden camera
0:34
_vector_
Рет қаралды 59 МЛН
Интереснее чем Apple Store - шоурум BigGeek
0:42
Очиститель экрана • 160418185                       Делюсь обзорами в профиле @lykofandrei
0:14
ПОКУПКА ТЕЛЕФОНА С АВИТО?🤭
1:00
Корнеич
Рет қаралды 347 М.