SlideShare une entreprise Scribd logo
1  sur  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

Contenu connexe

Tendances

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
 

Tendances (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)
 

En vedette (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
 

Similaire à Java concurrency introduction

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

Similaire à 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
 

Dernier

+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
?#DUbAI#??##{{(☎️+971_581248768%)**%*]'#abortion pills for sale in dubai@
 
Why Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businessWhy Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire business
panagenda
 

Dernier (20)

+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
 
Why Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businessWhy Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire 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
 
AWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of TerraformAWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of Terraform
 
AXA XL - Insurer Innovation Award Americas 2024
AXA XL - Insurer Innovation Award Americas 2024AXA XL - Insurer Innovation Award Americas 2024
AXA XL - Insurer Innovation Award Americas 2024
 
Ransomware_Q4_2023. The report. [EN].pdf
Ransomware_Q4_2023. The report. [EN].pdfRansomware_Q4_2023. The report. [EN].pdf
Ransomware_Q4_2023. The report. [EN].pdf
 
"I see eyes in my soup": How Delivery Hero implemented the safety system for ...
"I see eyes in my soup": How Delivery Hero implemented the safety system for ..."I see eyes in my soup": How Delivery Hero implemented the safety system for ...
"I see eyes in my soup": How Delivery Hero implemented the safety system for ...
 
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
 
DBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor PresentationDBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor Presentation
 
A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?
 
Apidays Singapore 2024 - Scalable LLM APIs for AI and Generative AI Applicati...
Apidays Singapore 2024 - Scalable LLM APIs for AI and Generative AI Applicati...Apidays Singapore 2024 - Scalable LLM APIs for AI and Generative AI Applicati...
Apidays Singapore 2024 - Scalable LLM APIs for AI and Generative AI Applicati...
 
Corporate and higher education May webinar.pptx
Corporate and higher education May webinar.pptxCorporate and higher education May webinar.pptx
Corporate and higher education May webinar.pptx
 
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
 
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost SavingRepurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
 
presentation ICT roal in 21st century education
presentation ICT roal in 21st century educationpresentation ICT roal in 21st century education
presentation ICT roal in 21st century education
 
A Beginners Guide to Building a RAG App Using Open Source Milvus
A Beginners Guide to Building a RAG App Using Open Source MilvusA Beginners Guide to Building a RAG App Using Open Source Milvus
A Beginners Guide to Building a RAG App Using Open Source Milvus
 
Navi Mumbai Call Girls 🥰 8617370543 Service Offer VIP Hot Model
Navi Mumbai Call Girls 🥰 8617370543 Service Offer VIP Hot ModelNavi Mumbai Call Girls 🥰 8617370543 Service Offer VIP Hot Model
Navi Mumbai Call Girls 🥰 8617370543 Service Offer VIP Hot Model
 
Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...
Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...
Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...
 
ICT role in 21st century education and its challenges
ICT role in 21st century education and its challengesICT role in 21st century education and its challenges
ICT role in 21st century education and its challenges
 
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWEREMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
 

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