Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to analyze the Art and concurrent programming of java concurrent programming

2025-01-19 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Internet Technology >

Share

Shulou(Shulou.com)06/01 Report--

This article to share with you is about how to analyze Java concurrent programming art and concurrent programming, Xiaobian feel quite practical, so share to everyone to learn, I hope you can read this article after some harvest, not much to say, follow Xiaobian to see it.

The Art of Java Concurrent Programming

Usually when we use compilation programming, the main purpose is to make the program faster, but it does not mean that more threads will make the program fast enough. Sometimes too many threads consume more resources, but make the program execute more slowly.

1

1.CPU context switching

Even if a single-core CPU is capable of handling multithreaded tasks, it just keeps switching threads to execute, making us feel multithreaded execution.

Below is a comparison of serial and concurrent execution time.

From the diagram we can see that when the number does not reach tens of millions, the serial and parallel time is almost the same, this is because the thread creation and context switch requires a certain amount of time overhead.

How to reduce context switching seems to be one of the things we need to pay attention to when programming concurrently.

Lockless programming, multi-thread concurrent strong lock, will cause frequent context switching, we can use a segmented approach to processing data, different threads processing different segments of data, avoid the use of locks

Use minimal threads. Avoid creating a large number of invalid threads, the task load is small, will leave a large number of threads in the waiting state, waste resources

2

II. Multithreading in Java

volatile and synchronize

Two things happen when we use the volatile variable modifier:

1. Data from the current processor is written back to system memory

2. This writeback invalidates the memory address in the processor

What do these two things mean? In java, volatile allows multiple threads to share a variable. When multiple threads get this variable, the thread will wait for the thread that is changing the variable to release it before reading it. This allows us to maintain uniqueness when multiple threads share this variable.

synchronized Foundation for synchronization

1. For normal methods, the lock is the current instance object

2. For static methods. The locked object is the current class object

3. For a method block, all objects in scope are locked

In layman's terms, an ordinary method lock is actually an instance object that is called. For this instance object, it is synchronous. If we have multiple instance objects calling its internal synchronous method at the same time, it is actually a concurrent request. For static methods, it only has one copy in Java, so no matter how many times it is called, it is a synchronous call. The final method block is similar to our ordinary method. The difference is that all objects in the scope of the lock are locked and belong to the thread's private variables.

3

III. Two Key Problems of Concurrent Programming Model

1. How threads communicate

2. How to synchronize threads

Most of the time, we don't care about how threads communicate, we will encounter the problem of how to synchronize a variable between threads in actual programming. Using volatile to modify a variable is a very good method. In the jvm memory model after jdk8, the instance of the object is stored in the local stack. After a variable uses volatile, the reference of the object instance is still in the local memory, and the variable of the object is copied to the main memory for sharing, not private. Basically, each thread still has the memory address of this variable, but different memory addresses point to the same variable in main memory.

4

IV.Java concurrency containers and frameworks

ConcurrentHashMap implementation principle and use

ConcurrentHashMap is a thread-safe and efficient HashMap

Structure diagram of ConcurrentHashMap

ConcurrentHashMap is composed of Segment array structure and HashEntry array structure. Segment is a reentrant lock that plays the role of lock in ConcurrentHashMap;HashEntry is used to store key-value pair data. A ConcurrentHashMap contains a Segment array. Segment structure and HashMap similar, is an array and linked list structure. A Segment contains an array of HashEntries. Each HashEntry is an element of a linked list structure. Each Segment guards an element in the HashEntry array. When modifying the data of the HashEntry array, you must first obtain the corresponding Segment lock.

Block queues in Java

ArrayBlockingQueue: A bounded blocking queue consisting of an array structure.

LinkedBlockingQueue: A bounded blocking queue consisting of a linked list structure.

PriorityBlockingQueue: An unbounded blocking queue that supports priority ordering.

DelayQueue: An unbounded blocking queue implemented using priority queues.

SynchronousQueue: A blocking queue that does not store elements.

LinkedTransferQueue: An unbounded blocking queue consisting of a linked list structure.

LinkedBlockingDeque: A bidirectional blocking queue consisting of a linked list structure.

5

v. thread pool

Thread pools are the threading framework we use most, and their proper use can bring us many benefits

1. Reduce resource consumption and avoid creating threads repeatedly

2. Increase responsiveness, keep a certain amount of waiting threads, and don't have to recreate threads every time

3. Improve thread manageability

Here, I have to mention that Ali's java coding specification clearly points out that thread pools are not allowed to be created using Executors, but through ThreadPoolExecutor, which makes the students who write more clear about the running rules of thread pools and avoids the risk of resource exhaustion.

6

vi. Concurrent programming practices

Producer and consumer models

Using producer and consumer patterns in concurrent programming solves most concurrency problems. This pattern improves the overall processing speed of the program by balancing the work power of the producer and consumer threads. In the threaded world, producers are threads that produce data and consumers are threads that consume data. In multithreaded development, if the producer is fast and the consumer is slow, the producer must wait for the consumer to finish processing before continuing to produce data. In the same way, if consumers have more processing power than producers, consumers must wait for producers. To address this imbalance in production and consumption capacity, there is the producer and consumer model.

I wrote a simple production-consumption, but there was no synchronization lock and no sharing variable, so I had a consumer of minus one.

So I let this variable be shared among threads but threw an IllegalMonitorStateException, which basically means that throwing this exception means that a thread trying to wait on an object monitor or notify other threads waiting on the object monitor, but not owning the monitor, proves that there can only be one thread that actually operates on shared variables

Because we didn't do the lock right, we couldn't release it, so I implemented it with ReentrantLock.

The above is how to analyze the art of Java concurrent programming and concurrent programming, Xiaobian believes that some knowledge points may be seen or used in our daily work. I hope you can learn more from this article. For more details, please follow the industry information channel.

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Internet Technology

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report