SlideShare ist ein Scribd-Unternehmen logo
1 von 15
Java Concurrency Introduction yangwm http://t.sina.com.cn/yangwm
- Java Memory Model  - Thread coordinate and Synchronize - Lock Blocking and Contention  - Java Util Concurrent  - Fork/Join, Coroutine
Java Memory Model: 1. Atomicity, Visibility,Ordering 2. main memory, working memory  3, safe publication happends-before ordering: synchronized:Atomicity, Visibility,Ordering volatile:Visibility(access main memory),Ordering final java.util.concurrent.locks java.util.concurrent.atmoic ... ThreadLocal : keep state with a thread  cache objects which you need frequently
Thread coordinate and Synchronize:  interrupt:  throw InterruptedException  or Thread.currentThread().interrupt() synchronized vs lock Condition await() -> wait() signal() -> notify() signalAll() -> notifyAll() LockSupport park() unpark()
Lock Blocking : suspending spin-waiting
Lock Contention : 1.  减少锁持有的时间 2.  减少锁请求的频率 3.  采用共享锁取代独占锁 lock separate: read write  lock split  lock-free: cas
Java Util Concurrent : AtomicInteger: visibility: volatile  nonblocking: for(;;) + compare-and-swap(cpu instruct: read-modify-write)  ReentrantLock :  NonfairSync vs FairSync  ReentrantReadWriteLock : volatile int value; AbstractQueuedSynchronizer: synchronization state; blocking and unblocking threads Queues: CLH FutureTask, CountDownLatch, CyclicBarrier,  Exchanger
Amdahl's Law 1 / ((1 - P) + (P / N))  P is the proportion of a program that can be made parallel (1 − P) is the proportion that cannot be parallelized (remains serial) N is processors
remind batch simple process flow :  1. split uids to uid array 2. local cache check source(appkey)  for { 3. hash by uid  4. get jedis connection by hash  5. do something with jedis connection  6. release jedis connection  7. return resultBean and to json or xml  }
remind batch optimization process flow :  1. get jedis connection  while(1){ 2. get something message by queue  3. do something with jedis connection  } 4. get jedis connection  1. split uids to uid array 2. local cache check source(appkey)  for { 3. hash by uid  4. put something message to queue by hash  5. return resultBean and to json or xml  }
Concurrent Collection: ConcurrentMap : ConcurrentHashMap/ConcurrentSkipListMap queue: ConcurrentLinkedQueue  BlockingQueue: SynchronousQueue/ArrayBlockingQueue/LinkedBlockingQueue copy-on-write: CopyOnWriteArrayList/CopyOnWriteArraySet
ThreadPoolExecutor : power and flexible  1. strategy create and destory strategy handle workqueue task handle excess task hook function extend behaviour 2. Concrete Implement : 1 )当 workerCount 小于 corePoolSize 就新建线程,并处理请求 2 )当 workerCount 大于等于 corePoolSize ,把请求放入 workQueue 中,空闲线程就去从 workQueue 中取任务并处理 3 )当 workQueue 放不下新入的任务时,新建 worker 加入 pool ,并处理请求,如果 workerCount 大小撑到了 maximumPoolSize 就用 RejectedExecutionHandler 来做拒绝处理
Fork/Join Framework  Fork/Join parallelism is among the simplest and most effective design techniques for obtaining good parallel performance. Result solve(Problem problem) { if (problem is small) { directly solve problem } else { split problem into independent parts fork new subtasks to solve each part join all subtasks compose result from subresults } }
Coroutine: Kilim is a message-passing framework for Java that provides ultra-lightweight threads and facilities for fast, safe, zero-copy messaging
thank you

Weitere ähnliche Inhalte

Was ist angesagt?

MongoUK 2011 - Rplacing RabbitMQ with MongoDB
MongoUK 2011 - Rplacing RabbitMQ with MongoDBMongoUK 2011 - Rplacing RabbitMQ with MongoDB
MongoUK 2011 - Rplacing RabbitMQ with MongoDB
Boxed Ice
 
Scalable Socket Server by Aryo
Scalable Socket Server by AryoScalable Socket Server by Aryo
Scalable Socket Server by Aryo
Agate Studio
 
Connecting to the network
Connecting to the networkConnecting to the network
Connecting to the network
Mu Chun Wang
 
ToroDB: scaling PostgreSQL like MongoDB / Álvaro Hernández Tortosa (8Kdata)
ToroDB: scaling PostgreSQL like MongoDB / Álvaro Hernández Tortosa (8Kdata)ToroDB: scaling PostgreSQL like MongoDB / Álvaro Hernández Tortosa (8Kdata)
ToroDB: scaling PostgreSQL like MongoDB / Álvaro Hernández Tortosa (8Kdata)
Ontico
 

Was ist angesagt? (20)

WiredTiger In-Memory vs WiredTiger B-Tree
WiredTiger In-Memory vs WiredTiger B-TreeWiredTiger In-Memory vs WiredTiger B-Tree
WiredTiger In-Memory vs WiredTiger B-Tree
 
HandlerSocket - A NoSQL plugin for MySQL
HandlerSocket - A NoSQL plugin for MySQLHandlerSocket - A NoSQL plugin for MySQL
HandlerSocket - A NoSQL plugin for MySQL
 
Elastic 101 tutorial - Percona Europe 2018
Elastic 101 tutorial - Percona Europe 2018 Elastic 101 tutorial - Percona Europe 2018
Elastic 101 tutorial - Percona Europe 2018
 
Being closer to Cassandra by Oleg Anastasyev. Talk at Cassandra Summit EU 2013
Being closer to Cassandra by Oleg Anastasyev. Talk at Cassandra Summit EU 2013Being closer to Cassandra by Oleg Anastasyev. Talk at Cassandra Summit EU 2013
Being closer to Cassandra by Oleg Anastasyev. Talk at Cassandra Summit EU 2013
 
톰캣 #09-쓰레드
톰캣 #09-쓰레드톰캣 #09-쓰레드
톰캣 #09-쓰레드
 
Open Source SQL databases enters millions queries per second era
Open Source SQL databases enters millions queries per second eraOpen Source SQL databases enters millions queries per second era
Open Source SQL databases enters millions queries per second era
 
System Capa Planning_DBA oracle edu
System Capa Planning_DBA oracle eduSystem Capa Planning_DBA oracle edu
System Capa Planning_DBA oracle edu
 
JavaScript Event Loop
JavaScript Event LoopJavaScript Event Loop
JavaScript Event Loop
 
MongoUK 2011 - Rplacing RabbitMQ with MongoDB
MongoUK 2011 - Rplacing RabbitMQ with MongoDBMongoUK 2011 - Rplacing RabbitMQ with MongoDB
MongoUK 2011 - Rplacing RabbitMQ with MongoDB
 
Scalable Socket Server by Aryo
Scalable Socket Server by AryoScalable Socket Server by Aryo
Scalable Socket Server by Aryo
 
Don't dump thread dumps
Don't dump thread dumpsDon't dump thread dumps
Don't dump thread dumps
 
Zookeeper소개
Zookeeper소개Zookeeper소개
Zookeeper소개
 
Connecting to the network
Connecting to the networkConnecting to the network
Connecting to the network
 
Vm
VmVm
Vm
 
MySQL async message subscription platform
MySQL async message subscription platformMySQL async message subscription platform
MySQL async message subscription platform
 
Embedded systems
Embedded systems Embedded systems
Embedded systems
 
NodeJS Concurrency
NodeJS ConcurrencyNodeJS Concurrency
NodeJS Concurrency
 
ToroDB: scaling PostgreSQL like MongoDB / Álvaro Hernández Tortosa (8Kdata)
ToroDB: scaling PostgreSQL like MongoDB / Álvaro Hernández Tortosa (8Kdata)ToroDB: scaling PostgreSQL like MongoDB / Álvaro Hernández Tortosa (8Kdata)
ToroDB: scaling PostgreSQL like MongoDB / Álvaro Hernández Tortosa (8Kdata)
 
Как понять, что происходит на сервере? / Александр Крижановский (NatSys Lab.,...
Как понять, что происходит на сервере? / Александр Крижановский (NatSys Lab.,...Как понять, что происходит на сервере? / Александр Крижановский (NatSys Lab.,...
Как понять, что происходит на сервере? / Александр Крижановский (NatSys Lab.,...
 
Масштабируемая конфигурация Nginx, Игорь Сысоев (Nginx)
Масштабируемая конфигурация Nginx, Игорь Сысоев (Nginx)Масштабируемая конфигурация Nginx, Игорь Сысоев (Nginx)
Масштабируемая конфигурация Nginx, Игорь Сысоев (Nginx)
 

Andere mochten auch (7)

Hbase introduction
Hbase introductionHbase introduction
Hbase introduction
 
Bigtable
BigtableBigtable
Bigtable
 
BigTable And Hbase
BigTable And HbaseBigTable And Hbase
BigTable And Hbase
 
Big table
Big tableBig table
Big table
 
Summary of "Google's Big Table" at nosql summer reading in Tokyo
Summary of "Google's Big Table" at nosql summer reading in TokyoSummary of "Google's Big Table" at nosql summer reading in Tokyo
Summary of "Google's Big Table" at nosql summer reading in Tokyo
 
NoSQL Databases: Why, what and when
NoSQL Databases: Why, what and whenNoSQL Databases: Why, what and when
NoSQL Databases: Why, what and when
 
Introduction to NoSQL Databases
Introduction to NoSQL DatabasesIntroduction to NoSQL Databases
Introduction to NoSQL Databases
 

Ähnlich wie Java concurrency introduction

Concurrency Learning From Jdk Source
Concurrency Learning From Jdk SourceConcurrency Learning From Jdk Source
Concurrency Learning From Jdk Source
Kaniska Mandal
 

Ähnlich wie Java concurrency introduction (20)

Ch10.애플리케이션 서버의 병목_발견_방법
Ch10.애플리케이션 서버의 병목_발견_방법Ch10.애플리케이션 서버의 병목_발견_방법
Ch10.애플리케이션 서버의 병목_발견_방법
 
Jmx capture
Jmx captureJmx capture
Jmx capture
 
What`s new in Java 7
What`s new in Java 7What`s new in Java 7
What`s new in Java 7
 
Introduction+To+Java+Concurrency
Introduction+To+Java+ConcurrencyIntroduction+To+Java+Concurrency
Introduction+To+Java+Concurrency
 
Threading in java - a pragmatic primer
Threading in java - a pragmatic primerThreading in java - a pragmatic primer
Threading in java - a pragmatic primer
 
Java util concurrent
Java util concurrentJava util concurrent
Java util concurrent
 
Here comes the Loom - Ya!vaConf.pdf
Here comes the Loom - Ya!vaConf.pdfHere comes the Loom - Ya!vaConf.pdf
Here comes the Loom - Ya!vaConf.pdf
 
Concurrency Learning From Jdk Source
Concurrency Learning From Jdk SourceConcurrency Learning From Jdk Source
Concurrency Learning From Jdk Source
 
Java 8 고급 (4/6)
Java 8 고급 (4/6)Java 8 고급 (4/6)
Java 8 고급 (4/6)
 
JS everywhere 2011
JS everywhere 2011JS everywhere 2011
JS everywhere 2011
 
Concurrency in Java
Concurrency in  JavaConcurrency in  Java
Concurrency in Java
 
Java Multithreading and Concurrency
Java Multithreading and ConcurrencyJava Multithreading and Concurrency
Java Multithreading and Concurrency
 
Thread & concurrancy
Thread & concurrancyThread & concurrancy
Thread & concurrancy
 
Everything you wanted to know about writing async, concurrent http apps in java
Everything you wanted to know about writing async, concurrent http apps in java Everything you wanted to know about writing async, concurrent http apps in java
Everything you wanted to know about writing async, concurrent http apps in java
 
Nodejs Intro Part One
Nodejs Intro Part OneNodejs Intro Part One
Nodejs Intro Part One
 
Java tips
Java tipsJava tips
Java tips
 
Session 24 - JDBC, Intro to Enterprise Java
Session 24 - JDBC, Intro to Enterprise JavaSession 24 - JDBC, Intro to Enterprise Java
Session 24 - JDBC, Intro to Enterprise Java
 
JDBC Part - 2
JDBC Part - 2JDBC Part - 2
JDBC Part - 2
 
Server side JavaScript: going all the way
Server side JavaScript: going all the wayServer side JavaScript: going all the way
Server side JavaScript: going all the way
 
Indic threads pune12-java ee 7 platformsimplification html5
Indic threads pune12-java ee 7 platformsimplification html5Indic threads pune12-java ee 7 platformsimplification html5
Indic threads pune12-java ee 7 platformsimplification html5
 

Kürzlich hochgeladen

Kürzlich hochgeladen (20)

GenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationGenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day Presentation
 
Boost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityBoost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivity
 
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
 
Exploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone ProcessorsExploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone Processors
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected Worker
 
Strategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherStrategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a Fresher
 
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
 
HTML Injection Attacks: Impact and Mitigation Strategies
HTML Injection Attacks: Impact and Mitigation StrategiesHTML Injection Attacks: Impact and Mitigation Strategies
HTML Injection Attacks: Impact and Mitigation Strategies
 
A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)
 
Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...
 
Advantages of Hiring UIUX Design Service Providers for Your Business
Advantages of Hiring UIUX Design Service Providers for Your BusinessAdvantages of Hiring UIUX Design Service Providers for Your Business
Advantages of Hiring UIUX Design Service Providers for Your Business
 
Automating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps ScriptAutomating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps Script
 
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationFrom Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
 
2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...
 
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
 
Real Time Object Detection Using Open CV
Real Time Object Detection Using Open CVReal Time Object Detection Using Open CV
Real Time Object Detection Using Open CV
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected Worker
 
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot TakeoffStrategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
 
Scaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationScaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organization
 
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
 

Java concurrency introduction

  • 1. Java Concurrency Introduction yangwm http://t.sina.com.cn/yangwm
  • 2. - Java Memory Model - Thread coordinate and Synchronize - Lock Blocking and Contention - Java Util Concurrent - Fork/Join, Coroutine
  • 3. Java Memory Model: 1. Atomicity, Visibility,Ordering 2. main memory, working memory 3, safe publication happends-before ordering: synchronized:Atomicity, Visibility,Ordering volatile:Visibility(access main memory),Ordering final java.util.concurrent.locks java.util.concurrent.atmoic ... ThreadLocal : keep state with a thread cache objects which you need frequently
  • 4. Thread coordinate and Synchronize: interrupt: throw InterruptedException or Thread.currentThread().interrupt() synchronized vs lock Condition await() -> wait() signal() -> notify() signalAll() -> notifyAll() LockSupport park() unpark()
  • 5. Lock Blocking : suspending spin-waiting
  • 6. Lock Contention : 1. 减少锁持有的时间 2. 减少锁请求的频率 3. 采用共享锁取代独占锁 lock separate: read write lock split lock-free: cas
  • 7. Java Util Concurrent : AtomicInteger: visibility: volatile nonblocking: for(;;) + compare-and-swap(cpu instruct: read-modify-write) ReentrantLock : NonfairSync vs FairSync ReentrantReadWriteLock : volatile int value; AbstractQueuedSynchronizer: synchronization state; blocking and unblocking threads Queues: CLH FutureTask, CountDownLatch, CyclicBarrier, Exchanger
  • 8. Amdahl's Law 1 / ((1 - P) + (P / N)) P is the proportion of a program that can be made parallel (1 − P) is the proportion that cannot be parallelized (remains serial) N is processors
  • 9. remind batch simple process flow : 1. split uids to uid array 2. local cache check source(appkey) for { 3. hash by uid 4. get jedis connection by hash 5. do something with jedis connection 6. release jedis connection 7. return resultBean and to json or xml }
  • 10. remind batch optimization process flow : 1. get jedis connection while(1){ 2. get something message by queue 3. do something with jedis connection } 4. get jedis connection 1. split uids to uid array 2. local cache check source(appkey) for { 3. hash by uid 4. put something message to queue by hash 5. return resultBean and to json or xml }
  • 11. Concurrent Collection: ConcurrentMap : ConcurrentHashMap/ConcurrentSkipListMap queue: ConcurrentLinkedQueue BlockingQueue: SynchronousQueue/ArrayBlockingQueue/LinkedBlockingQueue copy-on-write: CopyOnWriteArrayList/CopyOnWriteArraySet
  • 12. ThreadPoolExecutor : power and flexible 1. strategy create and destory strategy handle workqueue task handle excess task hook function extend behaviour 2. Concrete Implement : 1 )当 workerCount 小于 corePoolSize 就新建线程,并处理请求 2 )当 workerCount 大于等于 corePoolSize ,把请求放入 workQueue 中,空闲线程就去从 workQueue 中取任务并处理 3 )当 workQueue 放不下新入的任务时,新建 worker 加入 pool ,并处理请求,如果 workerCount 大小撑到了 maximumPoolSize 就用 RejectedExecutionHandler 来做拒绝处理
  • 13. Fork/Join Framework Fork/Join parallelism is among the simplest and most effective design techniques for obtaining good parallel performance. Result solve(Problem problem) { if (problem is small) { directly solve problem } else { split problem into independent parts fork new subtasks to solve each part join all subtasks compose result from subresults } }
  • 14. Coroutine: Kilim is a message-passing framework for Java that provides ultra-lightweight threads and facilities for fast, safe, zero-copy messaging