Java Synchronized

Memory Consistency Errors are common problems with Multi Thread Programming. In the tutorial, JavaSampleApproach will introduce you about Java Synchronized, is one of the solution for resolving problems related with Consistency Errors.

A. Concepts

When program has a shared resource with many threads, Memory Consistency Error will come when at a specific time, multi threads try to access the resource with 2 operations: read() & write() (called: Thread Interference). For facing with Thread Interference, Java provides a synchronized methodology that can apply on: synchronized method, synchronized statement( synchronized block).

B. Practice

I. Technologies

– Java 8
– Editor: Eclipse

II. Problem Sample

What happens with below programming? It will never terminate?

JavaSynchronized class:

Data class

A programming has a shared source: Data data, for increasing value of a member, the program sets up 10000 threads which each thread will increase value of a member by one unit.

Expected value of a member after 10000 thread is 10000. But base on theory, sometimes the result is not expected (not 10000) because of Memory Consistency Error by Thread Interference. So do-while statement will help to reproduce the problems:

synchronized method problems

III. Solution with Java Synchronized

Java Synchronized
will help programming resolving Memory Consistency Error.

– Solution with Java Synchronized Method
Apply for count() method of Data class.

– Solution with Java Synchronized Statement
Apply for body of count() method in Data class.

So now below code will never terminate:

IV. Sourcecode

Java Synchronized

By grokonez | December 17, 2016.

Last updated on June 4, 2017.

Related Posts

    Got Something To Say:

    Your email address will not be published. Required fields are marked *