preface

In the first two episodes, we introduced the basics of multi-threading. These are some of the most frequently asked interview questions. If you haven’t read them or have forgotten them, you can review them.

“Crouching pit can also enter Dachang” multi-thread these basic interview questions, 80% of small partners on the first question wrong

Multi-threaded series – context, deadlocks, high-frequency interview questions

This chapter focuses on analyzing the familiar Java memory model and introducing reordering, visibility, and communication between threads in a code way. You will definitely have a clearer understanding and understanding after reading this chapter.

Dog left son: flower Giegie ~, happy holiday ah! Coming to the pit so early.

I: oh, the dog left son you again today to work overtime, 365 days without rest you.

The dog remains son: this is not today festival, have no what good thing to give everybody to see an officer, can liver come out some dry goods to give brother people yao.

Me: Take that, dog.

The body of the

Me: I want you to tell us what volatile is.

Is that all you want to do here? You want us to think…

I: OK, small hot chicken, that I change a problem, did you ever understand JAVA memory model?

This is not the dog days to drink ice water, in the middle of the bosom?

The Java Memory Model, or JMM, is first known as a set of specifications for multithreaded access to Java Memory.

As we all know, there are many types of Java VMs on the market, such as HotSpot VM, J9 VM and various implementations (Oracle/Sun JDK, OpenJDK), and each VM has its own process for interpreting and reordering Java code. Without the JMM specification, It is quite possible that the same code interpreted by different JVMs will run inconsistently, which is not desirable.

Me: It’s kind of interesting, but it’s still a little vague. Can you tell me more about the specifications?

I know you’re going to ask me that. Guys, when we think of the Java memory model, we think of three parts first: reorder, visibility, and atomicity.

  • reorder

    Let’s take a look at a piece of code. I’ll give you a few minutes to see how many types of output this code has

    private static int x = 0, y = 0; private static int a = 0, b = 0; Thread one = new Thread(new Runnable() { @Override public void run() { a = 1; x = b; }}); Thread two = new Thread(new Runnable() { @Override public void run() { b = 1; y = a; }}); two.start(); one.start(); one.join(); two.join(); System.out.println("x = "+x+", y = "+y);

Is your answer one of these three

If so, then congratulations, you can continue to work with my dog on the fourth case

Here I added a for loop, you can print the loop until you want to print the result, you can run it yourself.

private static int x = 0, y = 0; private static int a = 0, b = 0; public static void main(String[] args) throws InterruptedException { int i = 0; for (; ;) { i++; x = 0; y = 0; a = 0; b = 0; CountDownLatch latch = new CountDownLatch(3); Thread thread1 = new Thread(new Runnable() { @Override public void run() { try { latch.countDown(); latch.await(); } catch (InterruptedException e) { e.printStackTrace(); } a = 1; x = b; }}); Thread thread2 = new Thread(new Runnable() { @Override public void run() { try { latch.countDown(); latch.await(); } catch (InterruptedException e) { e.printStackTrace(); } b = 1; y = a; }}); thread2.start(); thread1.start(); latch.countDown(); thread1.join(); thread2.join(); String result = "first" + I + "time (" + x +", "+ y +") "; if (x == 0 && y == 0) { System.out.println(result); break; } else { System.out.println(result); }}}

So let’s see how many times you do it. In this case, I’m doing it almost 170,000 times.

The reason why this happens is that there is a reorder, and after the reorder, the order of execution of the code is changed to:

  • y=2;
  • a=1;
  • x=b;
  • b=1;

In general, the order of code execution is not consistent with the order of code in the file. Code instructions are not executed strictly according to the order of code statements, but are adjusted according to their own rules. This is called reorder.

Me: There is something about this example. It is simple and clear. I understand it, right? What about visibility

Now, since the example is pretty straightforward, let me go ahead and use an example to explain a wave.

  • visibility
public class Visibility { int a = 1; int b = 2; private void change() { a = 3; b = a; } private void print() { System.out.println("b=" + b + "; a=" + a); } public static void main(String[] args) { while (true) { Visibility visibility = new Visibility(); // Thread 1 new Thread(() -> {try {Thread. Sleep (1); } catch (InterruptedException e) { e.printStackTrace(); } visibility.change(); }).start(); // Thread 2 new Thread(() -> {try {Thread. Sleep (1); } catch (InterruptedException e) { e.printStackTrace(); } visibility.print(); }).start(); }}}

If you think there are several kinds of print() results, you can understand them more deeply.

  • A =1, b=2: Thread 1 did not executechange(), thread 2 has already executedprint()
  • A =3, b=2: Thread 1 executes tochange()A = 3, then thread 2 executes exactlyprint()
  • A =3, b=3: Thread 1 has finished executingchange()Then thread 2 executesprint()

This is the most easy to think of and understand (if not, remember to take a refresher on the foundation of the first two chapters of the flower Gie), but there is a special case:

  • B = 3, a = 1

When thread 1 executes change(), a=3 and b=3, the result is only known to thread 1. To thread 2, it may only see part of the result. The reason for this is that there is a delay in communication between threads. And there is no real-time synchronization between multiple threads, so thread 2 only sees the latest value of b, but does not see the change of a.

Me: When you say that, I seem to understand a little, but not very clearly.

Can you say more about how this variable was passed, why thread 2 didn’t receive the change in A?

Okay, I’ll do whatever you want. I’ll just make a simple sketch.

<image width=300 src=”https://p6-juejin.byteimg.com/tos-cn-i-k3u1fbpfcp/69b6f4691db84a31805c0ee0016a45d9~tplv-k3u1fbpfcp-watermark.image” ></image>

<image width=300 src=”https://p9-juejin.byteimg.com/tos-cn-i-k3u1fbpfcp/c254ade514ce44c583b66ecf36e8c4c6~tplv-k3u1fbpfcp-watermark.image” ></image>

In the figure, we analyze the following four steps.

  • Each thread fetches variables from main memory and stores them in its own working memory (thread private), as shown in Figure 1Thread 1,Thread 2Initialization state;
  • Figure 2 shows thread 1 finishing executionchange()After the method, first willb=3Write back to main memory (at this pointa=3It has not been written back to main memory.)
  • Thread 2 fetches the latest data from main memoryA = 1, B = 3And write to its own worker thread
  • Thread 2 finally prints outa=1,b=3

Me: Now I understand. Please summarize the reasons for the visibility so that I can answer them in case the interviewer asks me.

.

The main reason for this visibility is that the CPU has multiple caches, and each thread reads the data it needs into the exclusive cache, writes the data to the cache after modification, and then waits for the data to be flushed back to the main memory. This causes some threads to read and write a value that is out of date.

Me: Kind of 6, I’ll give you a thumbs up, but what about atomicity?

I’ll come back to atomicity later, because it’s easier to learn about volatile and synchronized after we learn about them (do you think I’m not volatile?). I’m going to stop here. I’ve written so much that I don’t want to read it.

conclusion

JMM this just is very important, after mastering the screening questions, write demand will be more comfortable, we wanted to introduce some other more content, but to write down the space is too long, the effect is not very good, so these first, flower govemment also strongly recommend friends here can protect it personally, on paper will sleep shallow, Start to knock a knock after writing code will not be empty.

In the next chapter, HuaJi will continue to introduce happens-before, volatile, memory structure progression, etc. I hope you will keep your attention. The holiday ends tomorrow, and we will continue to live.

Keep your eyes on the ground

The above is the whole content of this issue, if there is a mistake, please comment, thank you very much. I’m Hua Ji, if you have any questions, please feel free to leave a message and discuss. See you at 🦮 next time.

The article is constantly updated, you can search on WeChat”
Java development zero to one“The first time to read, will continue to update the Java interview and all kinds of knowledge points, interested partners welcome to pay attention to, learn together, together ha 🐮.

If you think this article is useful to you, thank brother for liking, commenting or forwarding this article, because this will be the motivation for me to produce more good articles. Thank you!