search
HomeJavajavaTutorialjava concurrent programming (4) performance and scalability

java concurrent programming (4) performance and scalability

Jun 26, 2017 am 09:14 AM
javaScalabilityconcurrentperformanceprogramming

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> attributes = new HashMap<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);
    }</string></string>

 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);
        }
    }
}</string></string></string></string></string></string></string></string>

 

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 

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
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
Is java still a good language based on new features?Is java still a good language based on new features?May 12, 2025 am 12:12 AM

Javaremainsagoodlanguageduetoitscontinuousevolutionandrobustecosystem.1)Lambdaexpressionsenhancecodereadabilityandenablefunctionalprogramming.2)Streamsallowforefficientdataprocessing,particularlywithlargedatasets.3)ThemodularsystemintroducedinJava9im

What Makes Java Great? Key Features and BenefitsWhat Makes Java Great? Key Features and BenefitsMay 12, 2025 am 12:11 AM

Javaisgreatduetoitsplatformindependence,robustOOPsupport,extensivelibraries,andstrongcommunity.1)PlatformindependenceviaJVMallowscodetorunonvariousplatforms.2)OOPfeatureslikeencapsulation,inheritance,andpolymorphismenablemodularandscalablecode.3)Rich

Top 5 Java Features: Examples and ExplanationsTop 5 Java Features: Examples and ExplanationsMay 12, 2025 am 12:09 AM

The five major features of Java are polymorphism, Lambda expressions, StreamsAPI, generics and exception handling. 1. Polymorphism allows objects of different classes to be used as objects of common base classes. 2. Lambda expressions make the code more concise, especially suitable for handling collections and streams. 3.StreamsAPI efficiently processes large data sets and supports declarative operations. 4. Generics provide type safety and reusability, and type errors are caught during compilation. 5. Exception handling helps handle errors elegantly and write reliable software.

How do Java's Top Features Impact Performance and Scalability?How do Java's Top Features Impact Performance and Scalability?May 12, 2025 am 12:08 AM

Java'stopfeaturessignificantlyenhanceitsperformanceandscalability.1)Object-orientedprincipleslikepolymorphismenableflexibleandscalablecode.2)Garbagecollectionautomatesmemorymanagementbutcancauselatencyissues.3)TheJITcompilerboostsexecutionspeedafteri

JVM Internals: Diving Deep into the Java Virtual MachineJVM Internals: Diving Deep into the Java Virtual MachineMay 12, 2025 am 12:07 AM

The core components of the JVM include ClassLoader, RuntimeDataArea and ExecutionEngine. 1) ClassLoader is responsible for loading, linking and initializing classes and interfaces. 2) RuntimeDataArea contains MethodArea, Heap, Stack, PCRegister and NativeMethodStacks. 3) ExecutionEngine is composed of Interpreter, JITCompiler and GarbageCollector, responsible for the execution and optimization of bytecode.

What are the features that make Java safe and secure?What are the features that make Java safe and secure?May 11, 2025 am 12:07 AM

Java'ssafetyandsecurityarebolsteredby:1)strongtyping,whichpreventstype-relatederrors;2)automaticmemorymanagementviagarbagecollection,reducingmemory-relatedvulnerabilities;3)sandboxing,isolatingcodefromthesystem;and4)robustexceptionhandling,ensuringgr

Must-Know Java Features: Enhance Your Coding SkillsMust-Know Java Features: Enhance Your Coding SkillsMay 11, 2025 am 12:07 AM

Javaoffersseveralkeyfeaturesthatenhancecodingskills:1)Object-orientedprogrammingallowsmodelingreal-worldentities,exemplifiedbypolymorphism.2)Exceptionhandlingprovidesrobusterrormanagement.3)Lambdaexpressionssimplifyoperations,improvingcodereadability

JVM the most complete guideJVM the most complete guideMay 11, 2025 am 12:06 AM

TheJVMisacrucialcomponentthatrunsJavacodebytranslatingitintomachine-specificinstructions,impactingperformance,security,andportability.1)TheClassLoaderloads,links,andinitializesclasses.2)TheExecutionEngineexecutesbytecodeintomachineinstructions.3)Memo

See all articles

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

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

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools