Understanding Java Concurrent Processing (Introduction)

For example, have you implemented the following points in consideration of concurrency?

If you implement these codes without any consideration, they can cause ridiculous bugs in your production system. ** **

In this article, I would like to explain concurrency according to the following flow.

What is "concurrent processing"?

First, let's understand how Java works in memory.

"Process" and "Thread"

Various data for executing a program are stored in the memory space. Memory space is not shared between processes, but memory space is shared between threads. That is, ** different threads can access the same data. ** **

Types of thread processing

Of these, parallel processing and parallel processing correspond to "multithreading" that processes multiple threads at the same time. On the other hand, sequential processing is called "single thread" because it processes threads one by one.

One thing to watch out for is ** concurrency **. Since multiple threads share memory space with each other, if threads are executed at the same time, the data being read and written by one thread may be read and written by the other thread.

リソースへの同時アクセス

[IPA ISEC Secure Programming Course: C / C ++ Language Edition Chapter 4 Countermeasures for Unforeseen Conditions: General Countermeasures for Race Conditions](https://www.ipa.go.jp/security/awareness/vendor/programmingv2/contents /c304.html)

Why Concurrency Should Be Considered

Let's look at why we should consider concurrency through an example.

For example, suppose you have the following library rental reservation system. At this time, the number of reservations for the book "Java Concurrent Programming" is assumed to be 0 at this time.

  1. Get the number of reservations
  2. Add 1 to the number of reservations obtained
  3. Process the number of people booked 2. Update with the value in 2.

What if Alice and Bob booked "Java Concurrency Programming" at the same time? Depending on the timing, the processing may be executed in the following order.

Alice and Bob, who both believe that they booked earlier than anyone else, visited the library the next day and got into a fight.

As in the above example, a bug that occurs when data that was not supposed to be accessed at the same time is actually accessed in parallel by multiple threads ** "Race condition" It is called "**". The range that a program needs to operate in a single thread is called the ** "critical section" **.

On the other hand, a program that works normally even if it is called from multiple threads at the same time is referred to as ** "thread safe" **.

Thread-safe variables and non-thread-safe variables

In Java, some variables are thread-safe and some are not. I would like to explain how these variables work in memory.

Variable type

public class ClassSample{

	private String foo; //Instance variables
	private static String bar; //Class variables

	public static void methodSample(){
		
		int num = 1; //Local variables
		
	}
}

Of these variables, ** only local variables ** are thread-safe.

Thread-safe variables

Since local variables are stored in an area on the memory space called ** "stack area" ** that is unique to each thread, they can only be accessed by one thread. Therefore, other threads do not rewrite the information or mistakenly refer to the information.

Variables that are not thread-safe

Instance variables and class variables are shared by multiple threads ** Since data is held in an area on the memory space called "heap area" **, other threads rewrite information or refer to information by mistake. You may do it.

ローカル変数以外は複数のスレッドから共有され得る

[Implementation] Don't forget to make it thread-safe | Nikkei xTECH (Cross Tech)

Also, pay attention to the <%!%> Tag of ** JSP used when declaring variables and methods. The ** <%!%> Tag is not thread-safe as it expands as a Servlet ** instance variable ** when the JSP is compiled.

Concurrency is difficult to test

Race conditions are timing bugs that are very difficult to detect in ** tests. ** **

Brian Goetz (Java Architect, Oracle, as of March 2018), a leading expert in Java concurrency, wrote an article about concurrency. In "Java Theory and Practice: Surely Kill Bugs" Is mentioned.

Not surprisingly, writing code is the best time to make your code of high quality. This is because I have the best understanding of what works and how it works at this time.

** In order not to embed race conditions, programming and review should be done by a programmer who understands concurrency **.

The article recommends FindBugs as a partially but effective tool for detecting concurrency bugs. "Spotbugs", the successor to "FindBugs", has several items to detect race conditions. ("SpotBugs Manual, Details of Detectable Bugs")

Facebook also released ** "RacerD" **, a static analysis tool for Java concurrency bugs, as open source in October 2017. Please have a look as it is introduced in the following article.

I tried the Java concurrency bug analysis tool "RacerD" made by Facebook --Qiita

Summary

Reference book

Reference website

Recommended Posts

Understanding Java Concurrent Processing (Introduction)
[Java] Introduction
Server processing with Java (Introduction part.1)
Java thread processing
Java string processing
Introduction to java
[Java] Multi-thread processing
[Java] Stream processing
java iterative processing
Java Performance Chapter 1 Introduction
JAVA constructor call processing
Introduction to java command
Java random, various processing
[Java] Multi-thread processing --Exclusive control
[Java] Beginner's understanding of Servlet-②
[Java] Beginner's understanding of Servlet-①
[Java] Introduction to lambda expressions
[Java] Stream API --Stream termination processing
[Java] Stream API --Stream intermediate processing
[Java] Timer processing implementation method
Measured parallel processing in Java
[Java] Introduction to Stream API
Summary of java error processing
[Introduction to rock-paper-scissors games] Java
100% Pure Java BDD with JGiven (Introduction)
[Introduction to Java] About lambda expressions
[Introduction to Java] About Stream API
Date processing in Java (LocalDate: Initialization)
Delegate some Java processing to JavaScript
[Java] Loop processing and multiplication table
Let's use Twilio in Java! (Introduction)
Introduction to Functional Programming (Java, Javascript)
Run node.js from android java (processing)
Introduction to Ruby processing system self-made
[Processing × Java] How to use variables
[Java] What is Concurrent Modification Exception?
Understanding equals and hashCode in Java
Surprisingly deep Java list inversion-Stream processing
Basic processing flow of java Stream
About file copy processing in Java
Notes on Android (java) thread processing
Step-by-step understanding of Java exception handling
Deleting files using recursive processing [Java]
[Processing × Java] How to use arrays
[Java] Processing time measurement method memo
[Java] Exception types and basic processing
[Introduction to Java] About iterative processing (while, do-while, for, extension for, break, continue)