How are the students in this lesson, we are going to learn the basics of synchronization.
Synchronization is a huge topic and we'll learn it with you during multiple lessons.
This is the first lesson about stress and presentations that will give you basic knowledge when you
create concurrent programs.
One of the most important things that you should care about is a synchronized access of multiple threats
to the critical errors.
What is critical sections will learn with you today in this lesson also will learn with your concepts
of monitor and mutex.
After this lesson, you will understand these two concepts where, well, I will explain to you what
is at tormey cooperation and what is not.
Once you understand, all this theory will jump to practical examples and will create our first program
with synchronized threats.
I will explain how a synchronized keyboard works with Marcedes, and at the end of the lesson I will
explain such methods as a way to notify and notify all.
All objects in Java have these methods.
Let's start to begin with.
Let's understand what a critical section is.
It is important for us to learn this first because the rest of what we are going to do in this lesson
is to synchronize access to critical sections.
That's why understanding of this term is critically important.
Imagine that you have multiple threats that are executed concurrently and there is block of code that
theoretically may be available simultaneously for two threats.
This means that in some point of time it might happen that two or more threats will interact with some
resource simultaneously that may cause mistakes in calculations and data.
Inconsistency.
In other words, critical section is a group of instructions that should be executed concurrently only
by a specific number of threats and performance specific operations.
Usually it is one threat, but as we keep learning to read into advanced level, you would understand
that sometimes we want to allow multiple threats to perform.
One operation was a resource and allow multiple threats to perform another operation.
For example, imagine that you have collection, let's say a list operation of the new elements, or
at least should not allow other threats.
Read value from any index at mass should block access for all of the threats to read elements from specific
index, because I can add new element in that position and that would cause there to be read by other
threats.
At the same time, there is no need to look at the threats in case all threats only read data from my
array list and don't change its state.
That's why I may allow as many threats as there exist to read data from our own list only until the
moment of adding new elements to contain that will count does it make sense.
Now let's understand what is an atomic operation.
Atomic comes from Greek word atom.
That literally means uncuttable in computer science.
Atomic operation is operations that is performed with single processing cycle.
In other words, atomic operation is an interrupted operation.
Let's understand this, an example.
Imagine that you perform an increment of your object's property and you want to update its state.
What this thing is, this atomic operation, it is not.
Why?
Because you have to read values that are stored in the piece of memory dictated to the class property
variable first.
After that you need to perform an increment and add one.
After that, you need to store the result of additions in some place, and only after that you need
to assign the result of increments to another variable.
Our class property is that clear.
So even such simple operation is the first glance like increment is not atomic, but in this case,
what is an atomic operation?
And simple words read and write.
Operations are atomic.
For example, assigning value to a variable is atomic operation removal value from array is atomic operation.
Assigning value is an atomic operation too.
Does it make sense also in general with a special package that contains only Tibs that execute not atomic
operations by nature, but actually execute operations that looks like atomic, for example?
You know, that increment and addition is not atomic operation by itself, but atomic integer, for
example, maybe from addition of another in synchronized manner to not allow any other threat interrupt
execution of the separation later in this course, will review is generally two concurrent atomic package
that contains such types of perform atomic operations.
Would it a great single ready now you know what is an atomic.
Atomic operations also know what a critical section is.
Let's look at example now so that you can understand the problem of performing non atomic operations
with multiple threats and why we need to synchronize access to critical section I open unsynchronized
incremented file.
Let's look at the main message here.
And I will say you before we start that the quote below is a spaghetti code because we don't use executer
in this example, considering the fact that by this moment in our course, we don't know.
Executor's, I will show you this example was BASIX, Red Cross and Runnable interface that we all know
later in this course, we'll show you another solution, which is, in my opinion, more elegant.
But I will show it to you once we execute our stoppered hacker, at least that will contain references
to ohmy threat objects, because I'm going to create 10000 thread objects when it's so many threads
objects to be able to demo issues that may happen in case with performing on atomic operation with multiple
threats have falu.
And you can see that in condition.
I verify that I made 10000 iterations on each iteration.
I create a new threat object with the following implementation of Runnable interface.
I increment my static int variables that is present in this class and I will perform this increment
10000 times.
So what value will be here once all threats will perform increment ten thousand times will look at the
answer in the minutes after that and look at reference of this threat to the common list of threats.
I need this to be able to request each threat to join main threat and make main threat, wait until
all other threats will be executed.
And again, you need to see this code to feel relief later when you will start to use executer, because
you will understand how executables would simplify interaction with multiple threats.
And in Body of the Loop, I start each threat after that.
And for each loop I ask each threat, the join main threat and make my main threat.
Wait until all other threats will be executed.
When all threats did incremented, we can print our variable to cancel and let's see.
Instead I will run program multiple times to let you see the issue.
Can you see that the result is not always 10000?
They understand why this is happening.
That is because at some moment of time, two threats enter this method simultaneously and both threats
read the same value of counter variable and each threat might increment.
But logically, this is two increments.
But in fact, once we get our right increment result from as a threat and we got lost update, is it
clear now and what to do and how to solve this issue?
You already can easily spot where critical section is.
We need to synchronize access of different threats to our critical section where we are careful not
optronics operation.
That's why I started the lesson from explanation of critical sections and atomic operations to make
sure that by this moment of time in our lesson, you would understand what I'm talking about.
Let's now try to solve this issue.
To solve this issue, we need to control concurrent access to the critical area, the basic to enjoy.
The key for this is synchronized keyword.
Let me open synchronized increment class.
This is similar example to the previous one was only one difference.
My increment method synchronized keyword here.
Let's run our program now multiple times.
And you can see now that I constantly have ten thousand and so is it is because this synchronized keyword
doesn't allow to stress access is block of code simultaneously.
That's why we just eliminated all possible errors.
How to synchronize keywords for X.
We need to understand this to create more complex solutions with better performance.
To understand how to synchronize keyboard works, we need to understand such important concepts in Montessori,
in programming as mutex and monitor.
Let's start from understanding of what Moneta is.
And once we learned what I wanted to ask, how explain the difference between the index and monitor
my own definition of monitor.
Sounds like this monitor is a mechanism to synchronize threads, access to critical sections.
More common definition from Wikipedia also includes other properties of monitor like ability to allow
stress to have both mutuel exclusion and the ability to wait for a critical condition.
By the way, mutuel exclusion is also churl from computer science and describes the property of.
Currency control, which should prevent a race condition by not allowing any threat, entering a political
section, if some as a threat currently executing the court of critical section somewhere, you married
another definition saying that monitor is a threat, safe class object or module that is partially also
makes sense.
We can use an object as a flag and as a monitor to indicate which threat captures and monitor of the
object and which threat released monitor of the object.
So injera monitor is implicitly associated with an object.
Let me support my explanation, which was analyzation.
Let's look at the example with my car.
Here is my only Rs5 that can reach 60 miles per hour in less than a three point five seconds.
This has nothing in common with multiscreen and yet.
But we will jump to the details.
So imagine that this car is a monitor and critical sections.
Here are accelerator pedal, brake pedal, steering wheel and so on.
I'm a threat.
And girlfriend of mine is another threat of execution.
Those threats can't simultaneously interact with.
It will be horrible sink in case me and your friend of mine will be pushing on different pedals simultaneously.
I can capture, monitor and do operations with the cars that they need.
I open the car and drive to an office.
And when I got back home, I released the monitor.
When the monitor is released and a threat, my girlfriend can take it and can go to the beauty salon,
for example.
Is it clear so far there are also some methods that allow to interact with, monitor their weight,
notify and notify all.
Wait.
MassArt is overloaded and has versions with arguments that time related arguments milliseconds and nanoseconds
zest masses inherited in all types from object class because all objects in Java implicitly extant object
class.
What these methods do.
Let's review an example.
Imagine that my girlfriend took a car and all of a sudden something happened with a car and it was stopped
unexpectedly.
She called me and asked me to pick up her with the car and help.
When I found her in the city, she went out of the car and let me in what she did.
She released more nature of the object temporarily and let me capture monitor.
She still has intention to drive further, but she just let me also perform some actions with the car.
And that is exactly what the weight method does.
It's just really this monitor and let us the capture monitor.
I was happy to discover that my girlfriend just didn't activate Immobiliser and the engine appeared
to be blocked.
I think that and told her that she can drive from wherever she needs.
What I did, I called notify Masset on the monitor, notify Masset makes all threats that we're waiting
are aware that they can proceed their work.
That means we use with Massata to let other threats perform some actions and modify the state of some
objects if needed, of some shared resources.
And after that, other threats should call notify Masset to update all threats that they've done.
Another example of wait and notify.
You're going to have coding exercises soon and there will be a task about readers and writers.
For example, readers interact with some buffer of memory where readers should find information to read
readers captions and monitor of buffer object and doesn't allow anyone to work with it.
Once readers read all information from Buffer and Buffer is empty, they're turned into the waiting
state and they wait until right to put your information into the buffer.
Once the writer finished its job and put all information and buffer it, notifies our readers that we're
in a weakened state by and notify all Masset on buffer object.
And now readers continue with information from Buffer and so on.
Notify all is a matter to notify not only once residents in waiting queue, but notify us all threats
that time in the waiting queue.
Hope that now you understood what is and wanted to know.
Let's understand the difference between two terms monitor and mutex.
Conceptually, these two terms are similar zooni difference is how they are implemented inside.
Usually the implementation of monitors is faster light weight since it is designed for multiple threaded
synchronization within the same process.
Also, usually it is provided by a framework library itself and not request the operating system.
Usually matrixes are provided by the operating system.
Kernell what is always Curnoe in simple words, it is a computer program at the core of the computer's
operating system and has complete control over everything in the system.
It also handles data processing instructions for the central processing unit.
It is a portion of the operating system code that is always resident in memory.
Usually libraries frameworks simply provide an interface to invoke mutex.
This makes them heavy weight slower, but allows us to achieve expected to result to synchronize threads
between each other and lock on.
Mutex from neutral exclusion is a mechanism that enforces limits on access to resource.
When there are many threats of execution, a lock is designed to enforce a mutual exclusion.
Concurrency Control Policy and Monitor consists of a mutex lock object and condition variables.
A condition variable essentially is a container of threats that are waiting for a certain condition
more.
Charters provide a mechanism for threats to temporarily give up exclusive access in order to wait for
some conditions to be met before gaining exclusive access and resuming their task.
So monitor is different than mutex, but they can be considered similar in the sense that the monitor
is built on top of mutex in this lesson we'll use to monitor transfers.
But just in case you heard that somebody uses mutex term, you'll really know the difference.
Now, let's look at the Korean example and we'll try to understand how monitor works, how synchronization
happens and practice example, a way to notify interaction.
Let's get back to synchronized examples that we already saw today.
There is one more method here that is similar to synchronized one.
Pay attention that this method doesn't have synchronized keywords in the same line was messed name,
but it contains synchronized block.
What is this?
So when you have synchronized Masad, it is fair to say that you captured the monitor of this object
of object which he used to Vogues and mastered.
But what object you used to walk in Inmarsat in this case and also how it works with static methods,
with static methods.
You capture Moneta of this class to create synchronized block.
You have to pass the reference to an object where you want to capture monitor right now.
And this block may enter only once read.
And once the threat will leave this block, it will release monitor of this class and the next threat
will enter this block and will capture monitor, of course, with synchronized methods.
That principle is the same, but you just have synchronized access to the whole method, and not only
for a specific part of it, why you might want to use synchronize blocks.
So this part of the spreading optimization, because it may be that actually not aligned in your methods
is a critical section.
Probably there are some operations that have multiple threads may perform in parallel.
That might be really different cases.
For example, here you will print some text to console or you just want to log that.
You enter this method and you want to log some message after critical section, or it can be some preparation
activities before the duration.
Anyway, log in print and text.
The console in this case is not a critical section.
This will not bring you to inconsistent state of your system.
That's why there is no need to make your threats, wait to do operations that they can do now without
waiting.
So all core outside of the synchronized block may be executed concurrently.
When you will create a certain program, always ask yourself, do I need to synchronize access to this
chunk of code or know what will happen if the threat will execute this code simultaneously?
And in case you discover that nothing bad would happen, do not with this code in synchronized lock,
because in this case you would improve performance of your app by not making your sweats.
Wait.
And when they shouldn't be waiting in general, this is rule of thumb to have a small synchronized block
as possible.
In case this method won't be static, you will capture monitor of another object.
In this case, you would capture monitor of this object, the one that invokes this method.
So these two methods now are similar.
What potential drawback you see in using synchronize locks with synchronized locks?
You can't capture a monitor in one place and release it completely in another place.
You can't describe synchronized lock in multiple methods, but there is so called a lock API that we
are going to learn all kinds.
Of course, that will allow you to capture more data in one place and release it somewhere else.
Now let's look at WAF not for example, I grouped all the classes related to this example in a separate
package.
Here was name with Latifi.
Let me open them a file and will start from one could imagine that I have some message.
I create object of this type and left some message to process it.
Let's have a look at the source code of message type message has one properties and describes its state.
It is called message and need this type fostering position because he already knows that string itself
immutable object.
Once a great object of type string.
I can't change it state.
That's why I created separate type that has API that allows me to update the state of the same object.
Also, there are two matters here.
Getter and setter.
That's it.
Let's get back to the demo file.
The second object that I create here is a reader object.
I pass a reference to the message object.
We are constructor.
After that I create a threat object based reference to the readers and name as threat as reader one
and start the threat.
Probably already understands its rather implements Runnable interface, and you're right where you source
code of reading type in a few seconds.
Also another reader and pay attention.
I pass the same message, object to the constructor.
This would be exactly the object that I would use for multiple threads.
Synchronization here I create another thread, object to his name reader to and run this thread.
So after this line we would have three threads running my main threat and to readers threats.
Let's learn what will be executed inside our readers around method.
As you can see, reader class implements Runnable Interface.
It has one property.
This is property of message type inside the one massive yet name of the thread for our demo purposes
to print its name to consult.
And after that I have synchronized S..
I didn't make synchronized maps because in this case all reader objects would have separate monitor
and need common monitoring.
There's a shared between two threats.
This is additional advantage of synchronized block because you can pass any object as a reference to
capture monitor.
And I have this massive object that is shared between two waiters.
So I kept your monitor off message object.
After that, I claim to cancel and indicate that this threat is waiting to be notified and Prince Current
milliseconds after that I go wait Masad on my message object.
One more important thing you can call way Massud only in specific context.
You can call this method only from synchronized sections and from synchronized methods in case you would
invoke weight.
Massive note in synchronized context, you will get runtime exception with name, illegal and interstate
exception because Red is not an owner of a monitor.
Once I call Weight Masset, this thread is in the waiting queue to proceed execution when it will be
notified.
At the same time, the second reader managed to enter this section.
Considering the first reader called Wait Masset on monitor, that means that the monitor is not blocked
and another reader can enter the section.
Now it is time to learn what is happening next.
Let's get back to our demo file.
Now it's time to create a notifier object.
Notifier type is my custom type that I also described in this package.
Pay attention that I pass the reference to the same message object.
Great.
A threat was named Notifier and started after that.
I printed all threads I started.
Let's investigate what this notified do.
As you can see, objects of this type also will store as a reference to the message object.
This is our monitor.
In one method we get the name of the threat and indicate that this threat started its work after Z,
I made this threat sleep for one hundred milliseconds.
This is to ensure that the reader objects captured monitor first.
Once the threat wakes up, I try to enter, synchronize the book and undo any other threat is captured
in message monitor.
All other threats, including this one will stay right before the critical section and would not enter
it until get notified from the threats that the monitor is released.
You remember that in other threats we invoked.
Wait Massett.
That means that Notifier may enter this section and capture Monisha.
In this critical section.
We perform message processing.
We change the text to indicate which Notifier updated the message.
And after that I invoke is to notify or notify all assets in case I would invoke notify massive on the
one threat will be notified.
Is a reader one or reader.
So let's check this.
I run them a file.
Here is a notification about we do once read started notify us.
Threats started here and we are to start started and waiting to get notified here at this time.
And once I called notify MassArt reader finished its execution.
So now you can see that we do one, get notified and read other one message.
Protest in the source code of reader class.
You can see that I print this text to console after wait Macit at the end of round method.
So often defecation all code that is below.
Wait Massata got executed.
Pay attention that our game isn't stopped yet.
You can see this red stop sign that tells us that I can stop game but it is run.
But why another idle threat is working now.
It actually does nothing at the moment.
It is just waiting to be notified in this line.
But only we know that there are no threats left in the app right now that would be able to notify us
with their object all as a threat.
I mean, the main threat with the one threat notifier already executed and finished, and this is the
last threat that is waiting right now.
Let me stop again if you know that such case may happen, in case you know that two more threats might
enter a critical section and wait until being notified, you should think about your multiscreen logic
very carefully to avoid cases like this.
One thread is waiting as low as a threat, always a threat.
How to figure this?
You should control how many times you call Wakamatsu and how many times you call notify Mass.
Considering we have one point in our app where we call notify MassArt in our single Notify Threat and
we have to either objects where we call with Macit.
Let's invoke notify all Massett in our notify I open, notify a class and will invoke notify all Masset
instead simply notify Mass.
Let's run our F one more time.
Now you can see that all threats finished their work and no other threats running.
We have both.
Neither one and we are to notify.
You can verify this when instigation of console output is clear.
It is great that now you know how to work with notified masses and synchronization basics.
Let's recap what we have learned in this lesson.
In this lesson we learned what critical section is.
You understood what atomic and atomic operations are.
And we are still going to learn with you.
Jabiri two concurrent atomic package in the next lessons.
So stay tuned.
Now, you know what monitor and mutex are and what is the difference between them?
Also, you know what a synchronized method and what a synchronized block.
And at the end of the lesson, we have learned what weight notify and notify all methods are.
That's all for today, hope you enjoyed this lesson.
Thank you for your attention.
See you in the next lesson.