sleep and call method Assignment Help

Assignment Help: >> Synchronized Methods - sleep and call method

sleep and call method:

As you could see, through calling sleep ( ), the call ( ) method permits exception to switch to another thread. This results in the mixed-up output of the three message strings. Within program, nothing exists to stop all three threads from calling the similar method, on the similar object, at the similar time. That is known as a race condition, since the three threads are racing each other to done the method. This instance used sleep ( ) to make the effects repeatable and obvious. Within most conditions, a race condition is more subtle and less predictable, since you can't be sure when the context switch will occur. This could cause a program to run right one time and wrong the next.

To fix the preceding program, you must serialize access to call ( ). That is, you must restrict its access to only one thread at a time. To do this, you simply require preceding call ( )'s definition along with the keyword synchronized as displays here:

class Callme {

synchronized void call (String msg){

...

This avoids other threads from entering call ( ) although another thread is using it. After synchronized has been added to call( ), the output of the program is as given below:

[Hello] [Synchronized] [World]

Any time which you have a method, or group of methods, which manipulates the internal state of an object in a multithreaded condition, you should use the synchronized keyword to guard the state from race conditions.  Note that once a thread enters any synchronized method on an example, no other thread could enter any other synchronized methods on the similar instance.  Therefore, nonsynchronized functions on which instance will continue to be callable.

Free Assignment Quote

Assured A++ Grade

Get guaranteed satisfaction & time on delivery in every assignment order you paid with us! We ensure premium quality solution document along with free turntin report!

All rights reserved! Copyrights ©2019-2020 ExpertsMind IT Educational Pvt Ltd