Table of Contents
Performance and Scalability
1. Amdahl’s Law
2. Thread overhead
3. Reduce lock competition
 1. Reduce the lock holding time: reduce the scope of the lock
 2. Reduce the frequency of lock requests: lock decomposition and lock segmentation. ..
3. Avoid hot spots
4 .Replace exclusive locks
 5. Reduce context Switching
Home Java javaTutorial java concurrent programming (4) performance and scalability

java concurrent programming (4) performance and scalability

Jun 26, 2017 am 09:14 AM
java Scalability concurrent performance programming

Performance and Scalability

1. Amdahl’s Law

1. The relationship between problems and resources

In some problems, the more resources, the faster the solution ; Some problems are the opposite:

Note: Every program must have a serial part, and the impact of the serial and parallel parts on the program should be reasonably analyzed Extremely large; there is an exponential relationship between the proportion of the serial part and multi-core execution efficiency

2.ConcurrentLinkedQueue

In a multi-core environment, this thread-safe queue is faster than the queue generated through synchronizedList The speed is much faster

It can be said that the classes provided in concurrent are faster than the thread-safe classes generated by methods

2. Thread overhead

Since multi-threading has Overhead: Therefore, the use of multi-threading must ensure performance improvement>Concurrency overhead

Context switching overhead

Memory synchronization overhead

3. Reduce lock competition

 1. Reduce the lock holding time: reduce the scope of the lock

private final Map<String, String> attributes = new HashMap<String, String>();//整个方法上锁public synchronized boolean userLocationMatches(String name, String regexp) {
        String key = "users." + name + ".location";
        String location = attributes.get(key);if (location == null)return false;elsereturn Pattern.matches(regexp, location);
    }public boolean userLocationMatches(String name, String regexp) {
        String key = "users." + name + ".location";
        String location;//只针对可变状态上锁synchronized (this) {
            location = attributes.get(key);
        }if (location == null)return false;elsereturn Pattern.matches(regexp, location);
    }
Copy after login

 2. Reduce the frequency of lock requests: lock decomposition and lock segmentation. ..

  Lock decomposition: Decompose a lock into multiple locks. For example: there is no need to update multiple state variables in an atomic operation, but each state variable uses the same class lock, which is not necessary. Just use its own lock for each irrelevant state variable

public class ServerStatusBeforeSplit {public final Set<String> users;public final Set<String> queries;public ServerStatusBeforeSplit() {
        users = new HashSet<String>();
        queries = new HashSet<String>();
    }//每个方法使用 当前class实例锁,类似于synchronized(this),不管是否是操作同一共享状态public synchronized void addUser(String u) {
        users.add(u);
    }public synchronized void addQuery(String q) {
        queries.add(q);
    }public synchronized void removeUser(String u) {
        users.remove(u);
    }public synchronized void removeQuery(String q) {
        queries.remove(q);
    }
}public class ServerStatusAfterSplit {public final Set<String> users;public final Set<String> queries;//操作同一 状态的方法 使用相同的锁public ServerStatusAfterSplit() {
        users = new HashSet<String>();
        queries = new HashSet<String>();
    }public void addUser(String u) {synchronized (users) {
            users.add(u);
        }
    }public void addQuery(String q) {synchronized (queries) {
            queries.add(q);
        }
    }public void removeUser(String u) {synchronized (users) {
            users.remove(u);
        }
    }public void removeQuery(String q) {synchronized (users) {
            queries.remove(q);
        }
    }
}
Copy after login

 

Lock segmentation: For example, divide the map bucket into different segments , each segment has a lock. In this way, when performing certain operations such as get, you can hold different locks to improve concurrency efficiency. Of course, some operations need to hold the locks of all segments of the container at the same time, such as clear, etc.

//Map分段锁实现public class StripedMap {// Synchronization policy: buckets[n] guarded by locks[n%N_LOCKS]private static final int N_LOCKS = 16;  //锁数量private final Node[] buckets;           //容器桶private final Object[] locks;           //同步监听器对象数组private static class Node {
        Node next;
        Object key;
        Object value;
    }public StripedMap(int numBuckets) {
        buckets = new Node[numBuckets];
        locks = new Object[N_LOCKS];for (int i = 0; i < N_LOCKS; i++)
            locks[i] = new Object();
    }private final int hash(Object key) {return Math.abs(key.hashCode() % buckets.length);
    }public Object get(Object key) {int hash = hash(key);//获取当前 key对应的index区域的锁,只获取了一个锁synchronized (locks[hash % N_LOCKS]) {for (Node m = buckets[hash]; m != null; m = m.next)if (m.key.equals(key))return m.value;
        }return null;
    }public void clear() {for (int i = 0; i < buckets.length; i++) {//获取 每个i对应的锁,就是获取了整个容器所有的分段锁synchronized (locks[i % N_LOCKS]) {
                buckets[i] = null;
            }
        }
    }
}
Copy after login

3. Avoid hot spots

Performance problems caused by fierce lock competition for hot resources

4 .Replace exclusive locks

 For example: read-write lock: reading and reading can be parallelized to prevent exclusive use; use atomic state quantities; use concurrent containers; use immutable objects, etc.

 5. Reduce context Switching

Task switching between blocking and non-blocking states is similar to a context switch

For example: log, log printing and IO operations will cause a lot of blocking and release, resulting in poor performance question

The above is the detailed content of java concurrent programming (4) performance and scalability. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Roblox: Bubble Gum Simulator Infinity - How To Get And Use Royal Keys
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Nordhold: Fusion System, Explained
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Mandragora: Whispers Of The Witch Tree - How To Unlock The Grappling Hook
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Hot Topics

Java Tutorial
1666
14
PHP Tutorial
1273
29
C# Tutorial
1253
24
Break or return from Java 8 stream forEach? Break or return from Java 8 stream forEach? Feb 07, 2025 pm 12:09 PM

Java 8 introduces the Stream API, providing a powerful and expressive way to process data collections. However, a common question when using Stream is: How to break or return from a forEach operation? Traditional loops allow for early interruption or return, but Stream's forEach method does not directly support this method. This article will explain the reasons and explore alternative methods for implementing premature termination in Stream processing systems. Further reading: Java Stream API improvements Understand Stream forEach The forEach method is a terminal operation that performs one operation on each element in the Stream. Its design intention is

PHP: A Key Language for Web Development PHP: A Key Language for Web Development Apr 13, 2025 am 12:08 AM

PHP is a scripting language widely used on the server side, especially suitable for web development. 1.PHP can embed HTML, process HTTP requests and responses, and supports a variety of databases. 2.PHP is used to generate dynamic web content, process form data, access databases, etc., with strong community support and open source resources. 3. PHP is an interpreted language, and the execution process includes lexical analysis, grammatical analysis, compilation and execution. 4.PHP can be combined with MySQL for advanced applications such as user registration systems. 5. When debugging PHP, you can use functions such as error_reporting() and var_dump(). 6. Optimize PHP code to use caching mechanisms, optimize database queries and use built-in functions. 7

PHP vs. Python: Understanding the Differences PHP vs. Python: Understanding the Differences Apr 11, 2025 am 12:15 AM

PHP and Python each have their own advantages, and the choice should be based on project requirements. 1.PHP is suitable for web development, with simple syntax and high execution efficiency. 2. Python is suitable for data science and machine learning, with concise syntax and rich libraries.

PHP vs. Other Languages: A Comparison PHP vs. Other Languages: A Comparison Apr 13, 2025 am 12:19 AM

PHP is suitable for web development, especially in rapid development and processing dynamic content, but is not good at data science and enterprise-level applications. Compared with Python, PHP has more advantages in web development, but is not as good as Python in the field of data science; compared with Java, PHP performs worse in enterprise-level applications, but is more flexible in web development; compared with JavaScript, PHP is more concise in back-end development, but is not as good as JavaScript in front-end development.

PHP vs. Python: Core Features and Functionality PHP vs. Python: Core Features and Functionality Apr 13, 2025 am 12:16 AM

PHP and Python each have their own advantages and are suitable for different scenarios. 1.PHP is suitable for web development and provides built-in web servers and rich function libraries. 2. Python is suitable for data science and machine learning, with concise syntax and a powerful standard library. When choosing, it should be decided based on project requirements.

PHP's Impact: Web Development and Beyond PHP's Impact: Web Development and Beyond Apr 18, 2025 am 12:10 AM

PHPhassignificantlyimpactedwebdevelopmentandextendsbeyondit.1)ItpowersmajorplatformslikeWordPressandexcelsindatabaseinteractions.2)PHP'sadaptabilityallowsittoscaleforlargeapplicationsusingframeworkslikeLaravel.3)Beyondweb,PHPisusedincommand-linescrip

PHP: The Foundation of Many Websites PHP: The Foundation of Many Websites Apr 13, 2025 am 12:07 AM

The reasons why PHP is the preferred technology stack for many websites include its ease of use, strong community support, and widespread use. 1) Easy to learn and use, suitable for beginners. 2) Have a huge developer community and rich resources. 3) Widely used in WordPress, Drupal and other platforms. 4) Integrate tightly with web servers to simplify development deployment.

PHP vs. Python: Use Cases and Applications PHP vs. Python: Use Cases and Applications Apr 17, 2025 am 12:23 AM

PHP is suitable for web development and content management systems, and Python is suitable for data science, machine learning and automation scripts. 1.PHP performs well in building fast and scalable websites and applications and is commonly used in CMS such as WordPress. 2. Python has performed outstandingly in the fields of data science and machine learning, with rich libraries such as NumPy and TensorFlow.

See all articles