An object is an abstraction of a procedure, a thread-time scheduling abstraction.“- James O Coplien

1. Why concurrency

1. Concurrency is a decoupling strategy that helps us split what == does == (purpose) and when == does == (timing)

2. Decoupling purpose and timing can significantly improve the throughput and structure of an application compared to the tight coupling of single-threaded purpose and timing

3. Single-threaded programs that spend a lot of time waiting for Web socket I/O to end can improve performance by adopting multithreaded algorithms that access multiple sites simultaneously

There are also some side effects

  • Concurrency always improves performance: it only works when multiple threads or processors can share a lot of wait time
  • Write concurrent programs without changing the design: It may be very different from the design of a single-threaded system. Decoupling of purpose and timing often has a huge impact on system architecture
  • When adopting a Web or EJB container, understanding concurrency issues is not important (in fact, it’s better to know what the container is doing)

5. Pertinent statements about writing concurrent software:

  • Concurrency adds some overhead in terms of performance and writing extra code
  • Proper concurrency is complex, even for simple problems
  • Concurrency defects do not always recur, so they are often ignored as incidentals and not treated as true defects
  • Concurrency often requires a fundamental change in design strategy

2. The challenge

1. There are many possible paths for a thread to take while executing code, some of which produce incorrect results

public class X {
  private int lastIdUsed = 42;

  public int getNextId(a) {
    return++lastIdUsed; }}Copy the code

Run this code in two threads and you get three results

Thread1: 43 , Thread2: 44 , lastIdUsed: 44
Thread1: 44 , Thread2: 43 , lastIdUsed: 44
Thread1: 43 , Thread2: 43 , lastIdUsed: 43
Copy the code

From these three results, it can be seen intuitively that the concurrency problems caused by multithreading cannot always be repeated

Unexpected situations occur when two threads interact. This is because there are many possible paths for the thread to take when executing that line of Java code, some of which will produce incorrect results. Answering this question requires an understanding of how the just-in-time compiler treats the generated bytecode and what the Java memory model considers atomicity. (The answer is in understanding the Java Virtual Machine.)

In a nutshell, there are 12,870 different possible execution paths for the two threads executing in the getNextld method in terms of the generated bytecode. If the lastIdUsed type changes from int to long, the number of possible paths increases to 270,4156. Of course, most paths get the right answer. The problem is that some of them don’t get the right answer.

3. Concurrent defense

(1) Single responsibility principle SRP: separate concurrent related code from other code

(2) Limit data scope (remember data encapsulation; Severely restrict access to data that may be shared.)

(3) Use data copies

(4) Threads should be as independent as possible (try to decompose data into separate subsets that can be manipulated by separate threads (possibly on different processors)) (each thread handles a client request, accepts all request data from unshared sources and stores it as local variables)

4. Learn about Java libraries

  • Use thread-safe clustering provided by the class library
  • Use the Executor Framework to perform extraneous tasks
  • Use non-locking solutions whenever possible
  • Several classes are not thread-safe

Read the available classes. For Java, Java. Util. Concurrent, Java. Util. Concurrent. The atomic Java. Util. Concurrent. The locks

5. Understand the execution model

1. Some basic definitions

Limited resources Concurrent environments have fixed size or number of resources. For example, data connection
The mutex Only one thread can access shared data or resources at a time
Thread starvation When a thread or group of threads is disabled for an extended period of time or permanently, the fastest thread is always running, so that the slower one never gets a chance to execute
A deadlock Two or more threads are mutually exclusive and hold each other’s terminated resources
Live lock Threads that execute in the same order, each trying to start but finding that the other threads are already on the way, keep trying to start but fail for a long time because of race walking
2. There are roughly three types of multithreaded models, and most of the problems are variations of the problems existing in the three models
1. Producer-consumer model —- limited resources

2. Reader-author model —— Thread hunger and throughput degradation

3. Competitive systems —- deadlocks, live locks, throughput and efficiency

6. Beware of dependencies between synchronized methods

Avoid using more than one method for a shared object, and if you must, there are three countermeasures1. Client-based locking – The client code locks the server before calling the first method, ensuring that the scope of the lock covers the code calling the last method

2. Server-based locking – Create a method on the server to lock the client, call all methods, and unlock it

3. Match the server – Create the middle layer for locking

7. Keep the sync area small

The keyword synchronized created the lock. Locks are expensive.

All code areas maintained by the same lock are guaranteed to be executed by only one thread at any one time, because they introduce delays and extra overhead. == critical sections should be protected and designed as little as possible

8. Write the correct shutdown code carefully

1. Quiet shutdown is hard to do, and common problems have to do with deadlocks, threads waiting for signals that never come

2. Suggestion: Consider the shutdown as soon as possible and make it work properly as soon as possible

9. Test thread code

Testing does not guarantee correctness, however, good testing minimizes risk. This is true for all single-threaded solutions. Things get complicated when you have two or more threads using the same code snippet and sharing data.

  • Write tests that have the potential to expose problems and run them frequently under different programming configurations, system configurations, and load conditions. If the test fails, trace the error. Don’t ignore failures just because later tests pass later runs
  • Think of pseudo failures as possible threading problems: threaded code causes “impossible to fail” failures, and don’t blame system errors on happenings
  • Make non-threaded code work first: Do not track both non-threaded and thread defects, and make sure your code works outside of threads
  • Write pluggable thread code that can run in different configuration environments
  • Write thread code that is adjustable: Allows threads to self-adjust based on throughput and system utilization
  • Run more threads than the number of processors: The more frequently tasks are exchanged, the more likely it is to find code that missed critical regions causing deadlocks
  • Run on different platforms: Run threaded code on all target platforms early and often
  • Install trial-and-error code: add calls to object.wait (), object.sleep (), object.yield (), object.priority () and other methods, change code execution order, hard code or automation

Implement device code programmatically using tools such as aspect-oriented -Framework, CGLIB, or ASM tools

10. Summary

Follow SRP — > understand the possible causes of concurrent problems — > learn the class libraries, understand the basic algorithms — > learn how to find areas of code that must be locked and locked — > Problems pop up — > write device code to improve the chances of finding bad code

11. References

The way of clean code www.jianshu.com/p/c44eca6ad… zhuanlan.zhihu.com/p/37639722

Pay attention to the public account “Programmer interview”

Reply to “interview” to get interview package!!

This public account to share their own from programmer xiao Bai to experience spring recruitment autumn recruitment cut more than 10 offer interview written test experience, including [Java], [operating system], [computer network], [design mode], [data structure and algorithm], [Dacheng face by], [database] look forward to you join!!

1. Computer network —- Three times shake hands four times wave hands

2. Dream come true —– Project self-introduction

Here are the design patterns you asked for

4. Shocked! Check out this programmer interview manual!!

5. Teach you the interview “Profile” word for word

6. Nearly 30 interviews shared