CodeGym /Courses /Java Core /Multithreading problems: accessing a shared resource

Multithreading problems: accessing a shared resource

Java Core
Level 7 , Lesson 1
Available

"Hello, Amigo! Yesterday we discussed the benefits and conveniences of multithreading. Now it's time to look at the disadvantages. And, unfortunately, they are not small."

Previously, we looked at a program as a set of objects that call each other's methods. Now everything gets a little more complicated. A program is more like a set of objects that has several "small robots" (threads) crawling through it and executing the commands contained in the methods.

This new interpretation doesn't cancel the first. They are still objects, and they still call each other's methods. But we have to remember that there are several threads, and each thread does its own job or task.

A program is becoming more complicated. Different threads change the state of different objects based on the tasks they perform. And they can step on each other's toes.

But the worst stuff happens deep inside the Java machine. As I've said already, the apparent simultaneity of threads is achieved by the fact that the processor constantly switches from one thread to another. It switches to a thread, works for 10 milliseconds, switches to the next thread, works for 10 milliseconds, and so on. And herein lies the problem: these switches can occur at the most inopportune moments. Consider this example:

Code of the first thread Code of the second thread
System.out.print ("Nick is"); System.out.print (""); System.out.print ("15"); System.out.print (""); System.out.print ("years old");
System.out.println ();
System.out.print ("Lena is"); System.out.print (""); System.out.print ("21"); System.out.print (""); System.out.print ("years old");
System.out.println ();
What we expected to be displayed
Nick is 15 years old
Lena is 21 years old
Actual code execution Code of the first thread Code of the second thread
System.out.print ("Nick is");
System.out.print ("Lena is"); System.out.print (" ");
System.out.print (" "); System.out.print ("15");
System.out.print ("21"); System.out.print (" ");
System.out.print (" "); System.out.print ("years old"); System.out.println ();
System.out.print ("years old"); System.out.println ();
System.out.print ("Nick is");
//other thread is running
//other thread is running
System.out.print (" "); System.out.print ("15"); //other thread is running
//other thread is running
System.out.print (" "); System.out.print ("years old"); System.out.println ();
//other thread is running
//other thread is running
//other thread is running
System.out.print ("Lena is"); System.out.print (" ");
//other thread is running
//other thread is running
System.out.print ("21"); System.out.print (" ");
//other thread is running
//other thread is running
//other thread is running
System.out.print ("years old"); System.out.println ();
What is actually displayed
Nick is Lena is  15 21 years old
years old

And here's another example:

Code Description
class MyClass
{
private String name1 = "Ally";
private String name2 = "Lena";
public void swap()
{
String s = name1;
name1 = name2;
name2 = s;
}
}
The swap method swap the values of the name1 and name2 variables.

What might happen if it is called from two threads at the same time?

Actual code execution Code of the first thread Code of the second thread
String s1 = name1; //Ally
name1 = name2; //Lena
String s2 = name1; //Lena(!)
name1 = name2; //Lena
name2 = s1; //Ally
name2 = s2; //Lena
String s1 = name1; name1 = name2;
//other thread is running
//other thread is running
name2 = s1;
//other thread is running
//other thread is running
//other thread is running
String s2 = name1; name1 = name2;
//other thread is running
name2 = s2;
The bottom line
Both variables have the value «Lena».
The «Ally» object didn't make it. It's lost.

"Who would have guessed that errors like this are possible with such a simple assignment operation?!"

"Yes, this problem has a solution. But we'll talk about this a little later - my throat is dry."

Comments (19)
TO VIEW ALL COMMENTS OR TO MAKE A COMMENT,
GO TO FULL VERSION
Evgeniia Shabaeva Level 37, Budapest, Hungary
8 August 2024
So, we have a create a problem - we solve the problem - we create another problem by having solved the previous one - we solve the new problem - we create another one (endless loop!). :). Well, I can't quit now, I'm too absorbed into all this staff!
Jaques Strydom Level 23, Pretoria, South Africa
25 June 2024
I just realised how smart Amigo is. He actually complete the whole of Lesson 16 with all of the exercises in one day. 😶
manny9876 Level 36, Israel
28 April 2023
Talk about dry throat, my ears are hurting! Lol!
Tasmoda Level 28, Midrand, South Africa
12 July 2022
"It switches to a thread, works for 10 milliseconds, switches to the next thread, works for 10 milliseconds, and so on"--- You'd swear this statement is from Pentium 1 era. Sounds soo ancient.😂
Dmitri Level 22, Seversk, Russia
29 December 2020
if each thread is working with it's own MyClass instance why all this mess should happen? Why fields and the method in the example are not static?
Gellert Varga Level 23, Szekesfehervar, Hungary
27 April 2021
I figured it out not by myself... I just pass the answers from others: - In this example, two threads are working on the same single object. They want to modify the instance variables for the same object. - The class state (the variables name1 and name2) however can be corrupted when not coded as thread safe. - If a method does not change Object state (or any other shared resource) then it is implicitly thread safe. - Variables declared within a method (local variables) are not shared by threads. Also in the lesson example, the threads do not share the String s variable of the method, so this is not a variable in common. Each thread has its own instance of the s variable (notation s1, s2).
Jonaskinny Level 25, Redondo Beach, United States
25 April 2022
If you don't make a given set of statements thread-safe, any number of threads can enter, and their order of execution is not in your control. So if you want each thread to only affect an object's state during that thread's use of the object, you need to lock down state access to the object in whatever atomic definition suits your use case.
moseka Level 23, Nairobi, Kenya
1 July 2020
This video is so helpful to understand the point better https://www.youtube.com/watch?v=RH7G-N2pa8M
MaGaby2280 Level 41, Guatemala City, Guatemala
30 January 2020
These lessons are getting more expensive... it´s hard to earn 17 darkmatters ;o)
Justin Johnson Level 31, Clearwater, United States
1 February 2020
yeah only 1023 in the bank lol
Daniel Tinsley Level 22, United States, United States
11 November 2019
Just when you think you're finally past threads, there is more lol.
kiwii Level 37, United States
3 June 2019
Hello, guys! I make it here! Keep the momentum! Cannot wait to do the mini-projects and the interview session.
27 August 2019
I didn't know there are mini-projects nor an interview session. What level is that at?
kiwii Level 37, United States
28 August 2019
Check here Sir. Check the lessons. https://codegym.cc/quests/QUEST_JAVA_MULTITHREADING https://codegym.cc/quests/QUEST_JAVA_COLLECTIONS
28 August 2019
Thanks for the info, Kiwii. I see those are level 21+ hehe How about the interview prepping? you got to that part already? I've only found this so far:
kiwii Level 37, United States
1 September 2019
Above level 21+, every level has an interview lesson, usually in one of the last couple of lessons. For example, https://codegym.cc/quests/lectures?quest=QUEST_JAVA_MULTITHREADING&level=1, the lesson 15 is the interview questions.
Darko Jakimovski Level 18, Kriva Palanka, Macedonia, The Former Yugoslav Republic of
29 May 2019
Wasting my hard earned dark matter Ellie!