SlideShare uma empresa Scribd logo
1 de 41
J2SE 5.0 Concurrency,  ,[object Object],[object Object],[object Object]
Speaker’s Qualifications ,[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object]
Java Concurrency
Motivation for Concurrency Utilities ,[object Object],[object Object],[object Object],[object Object],[object Object],[object Object]
Concurrency Utilities Goals ,[object Object],[object Object],[object Object],[object Object]
Puzzle:  “Ping Pong” ,[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object]
What Does It Print? ,[object Object],[object Object],[object Object]
What Does It Print? ,[object Object],[object Object],[object Object],[object Object]
Example How to start a thread ,[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object]
Another Look ,[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object]
How Do You Fix It? ,[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object]
The Moral ,[object Object],[object Object],[object Object]
Concurrency Utilities: JSR-166 ,[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object]
Concurrency Utilities: JSR-166 ,[object Object],[object Object],[object Object],[object Object],public interface Executor { void execute (Runnable command); }
Executor Framework for asynchronous execution public interface  Executor  { void execute (Runnable command); } public interface  ExecutorService extends  Executor { .. } public class Executors {  //Factory methods static  ExecutorService  newFixedThreadPool(int poolSize); ... } Executor pool = Executors.newFixedThreadPool(5); pool.execute   ( runnable ) ;
Creating Executors ,[object Object],public class  Executors  { static ExecutorService newSingleThreadedExecutor (); static ExecutorService newFixedThreadPool (int poolSize); static ExecutorService newCachedThreadPool (); static ScheduledExecutorService newScheduledThreadPool (); //  Other methods not listed }
Thread Pool Example class WebService { public static void main(String[] args) { Executor pool = Executors.newFixedThreadPool(5); ServerSocket  socket  = new ServerSocket(999);  for (;;) {  final Socket  connection  = socket.accept(); Runnable  task  =  new Runnable() {  public void run() {  new   Handler().process ( connection );  } } pool.execute   ( task ) ;  }  }  }  class  Handler   { void  process (Socket s); }
ExecutorService for Lifecycle Support ,[object Object],public interface ExecutorService extends Executor { void  shutdown (); List<Runnable>  shutdownNow (); boolean  isShutdown (); boolean  isTerminated (); boolean  awaitTermination (long timeout, TimeUnit unit); //  additional methods not listed }
ScheduledExecutorService ,[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object]
ScheduledExecutorService Example ScheduledExecutorService sched =  Executors. newSingleThreadScheduledExecutor (); public void runTwiceAnHour(long howLong) { final Runnable rTask = new Runnable() { public void run() { /* Work to do */ } }; final  ScheduledFuture<?>  rTaskFuture = sched. scheduleAtFixedRate (rTask, 0, 1800, SECONDS); sched. schedule (new Runnable { public void run { rTaskFuture.cancel(true); } }, howLong, SECONDS); }
Synchronize Critical Section ,[object Object],[object Object],synchronized  double  getBalance()  { Account acct = verify(name, password); return acct.balance; } Lock held for long time double  getBalance()  { synchronized (this)   { Account acct = verify(name, password); return acct.balance; } } Current object is locked Equivalent to above double  getBalance()  { Account acct = verify(name, password); synchronized (acct)   { return acct.balance}; } Better Only acct object is locked – for shorter time
Locks ,[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object]
Lock Interface ,[object Object],Interface Lock { void  lock (); void  lockInterruptibly () throws  IE ; boolean  tryLock (); boolean  tryLock (long t, TimeUnit u) throws  IE ; //returns true if lock is aquired void  unlock (); Condition  newCondition () throws  UnsupportedOperationException; } IE = InterruptedException
RentrantLock ,[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object]
Lock Example Lock  lock = new RentrantLock(); public void accessProtectedResource()  throws IllegalMonitorStateException { lock.lock(); try { // Access lock protected resource } finally { // Ensure lock is always released lock.unlock(); } }
ReadWriteLock Interface ,[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object]
ReadWriteLock Example ReentrantReadWriteLock rwl = new  ReentrantReadWriteLock (); Lock rLock =  rwl.readLock (); Lock wLock =  rwl.writeLock (); ArrayList<String> data = new ArrayList<String>(); public String getData(int pos) { r.lock () ; try { return  data.get (pos); } finally {  r.unlock (); } } public void addData(int pos, String value) { w.lock (); try {  data.add (pos, value); } finally {  w.unlock (); } }
Synchronizers ,[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object]
BlockingQueue Interface ,[object Object],Interface BlockingQueue<E> { void  put (E o) throws IE; boolean  offer (E o) throws IE; boolean  offer (E o, long t, TimeUnit u) throws IE; E  take () throws IE; E  poll () throws IE; E  poll (long t, TimeUnit u) throws IE; int  drainTo (Collection<? super E> c); int  drainTo (Collection<? super E> c, int max); // Other methods not listed }
BlockingQueue Implementations ,[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object]
Blocking Queue Example: 1 private  BlockingQueue<String>   msgQueue ; public  Logger ( BlockingQueue<String>  mq) { msgQueue = mq; } public void run() { try { while (true) { String message =  msgQueue.take (); /*  Log message  */ } } catch (InterruptedException ie) { } }
Blocking Queue Example: 2 private  ArrayBlockingQueue messageQueue =  new ArrayBlockingQueue<String>(10); Logger logger = new Logger( messageQueue ); public void run() { String someMessage; try { while (true) { /*  Do some processing  */ /*  Blocks if no space available  */ messageQueue.put(someMessage) ; } } catch (InterruptedException ie) { } }
Concurrent Collections ,[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object]
Summary ,[object Object],[object Object],[object Object],[object Object]
For More Information
Resources and Summary
For More Information (1/2) ,[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object]
For More Information (2/2) ,[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object]
Resources ,[object Object],[object Object],[object Object]
Stay in Touch with Java SE  ,[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object]
Thank You! ,[object Object],[object Object],[object Object]

Mais conteúdo relacionado

Mais procurados

.NET Multithreading and File I/O
.NET Multithreading and File I/O.NET Multithreading and File I/O
.NET Multithreading and File I/OJussi Pohjolainen
 
Concurrency Programming in Java - 07 - High-level Concurrency objects, Lock O...
Concurrency Programming in Java - 07 - High-level Concurrency objects, Lock O...Concurrency Programming in Java - 07 - High-level Concurrency objects, Lock O...
Concurrency Programming in Java - 07 - High-level Concurrency objects, Lock O...Sachintha Gunasena
 
Java Concurrency, Memory Model, and Trends
Java Concurrency, Memory Model, and TrendsJava Concurrency, Memory Model, and Trends
Java Concurrency, Memory Model, and TrendsCarol McDonald
 
Java 5 concurrency
Java 5 concurrencyJava 5 concurrency
Java 5 concurrencypriyank09
 
JVM Mechanics: When Does the JVM JIT & Deoptimize?
JVM Mechanics: When Does the JVM JIT & Deoptimize?JVM Mechanics: When Does the JVM JIT & Deoptimize?
JVM Mechanics: When Does the JVM JIT & Deoptimize?Doug Hawkins
 
Java Garbage Collection, Monitoring, and Tuning
Java Garbage Collection, Monitoring, and TuningJava Garbage Collection, Monitoring, and Tuning
Java Garbage Collection, Monitoring, and TuningCarol McDonald
 
Java Concurrency in Practice
Java Concurrency in PracticeJava Concurrency in Practice
Java Concurrency in PracticeAlina Dolgikh
 
Java concurrency - Thread pools
Java concurrency - Thread poolsJava concurrency - Thread pools
Java concurrency - Thread poolsmaksym220889
 
Inter threadcommunication.38
Inter threadcommunication.38Inter threadcommunication.38
Inter threadcommunication.38myrajendra
 
Java concurrency
Java concurrencyJava concurrency
Java concurrencyducquoc_vn
 
Making Java more dynamic: runtime code generation for the JVM
Making Java more dynamic: runtime code generation for the JVMMaking Java more dynamic: runtime code generation for the JVM
Making Java more dynamic: runtime code generation for the JVMRafael Winterhalter
 
Basics of Java Concurrency
Basics of Java ConcurrencyBasics of Java Concurrency
Basics of Java Concurrencykshanth2101
 
Thread syncronization
Thread syncronizationThread syncronization
Thread syncronizationpriyabogra1
 
Inter thread communication &amp; runnable interface
Inter thread communication &amp; runnable interfaceInter thread communication &amp; runnable interface
Inter thread communication &amp; runnable interfacekeval_thummar
 

Mais procurados (20)

.NET Multithreading and File I/O
.NET Multithreading and File I/O.NET Multithreading and File I/O
.NET Multithreading and File I/O
 
Concurrency Programming in Java - 07 - High-level Concurrency objects, Lock O...
Concurrency Programming in Java - 07 - High-level Concurrency objects, Lock O...Concurrency Programming in Java - 07 - High-level Concurrency objects, Lock O...
Concurrency Programming in Java - 07 - High-level Concurrency objects, Lock O...
 
Java Concurrency, Memory Model, and Trends
Java Concurrency, Memory Model, and TrendsJava Concurrency, Memory Model, and Trends
Java Concurrency, Memory Model, and Trends
 
concurrency_c#_public
concurrency_c#_publicconcurrency_c#_public
concurrency_c#_public
 
Java 5 concurrency
Java 5 concurrencyJava 5 concurrency
Java 5 concurrency
 
JVM Mechanics: When Does the JVM JIT & Deoptimize?
JVM Mechanics: When Does the JVM JIT & Deoptimize?JVM Mechanics: When Does the JVM JIT & Deoptimize?
JVM Mechanics: When Does the JVM JIT & Deoptimize?
 
Java Garbage Collection, Monitoring, and Tuning
Java Garbage Collection, Monitoring, and TuningJava Garbage Collection, Monitoring, and Tuning
Java Garbage Collection, Monitoring, and Tuning
 
srgoc
srgocsrgoc
srgoc
 
Java Concurrency in Practice
Java Concurrency in PracticeJava Concurrency in Practice
Java Concurrency in Practice
 
Java Programming - 03 java control flow
Java Programming - 03 java control flowJava Programming - 03 java control flow
Java Programming - 03 java control flow
 
Java concurrency - Thread pools
Java concurrency - Thread poolsJava concurrency - Thread pools
Java concurrency - Thread pools
 
04 threads
04 threads04 threads
04 threads
 
Inter threadcommunication.38
Inter threadcommunication.38Inter threadcommunication.38
Inter threadcommunication.38
 
Java Concurrency by Example
Java Concurrency by ExampleJava Concurrency by Example
Java Concurrency by Example
 
Java concurrency
Java concurrencyJava concurrency
Java concurrency
 
Making Java more dynamic: runtime code generation for the JVM
Making Java more dynamic: runtime code generation for the JVMMaking Java more dynamic: runtime code generation for the JVM
Making Java more dynamic: runtime code generation for the JVM
 
Byte code field report
Byte code field reportByte code field report
Byte code field report
 
Basics of Java Concurrency
Basics of Java ConcurrencyBasics of Java Concurrency
Basics of Java Concurrency
 
Thread syncronization
Thread syncronizationThread syncronization
Thread syncronization
 
Inter thread communication &amp; runnable interface
Inter thread communication &amp; runnable interfaceInter thread communication &amp; runnable interface
Inter thread communication &amp; runnable interface
 

Semelhante a Java Concurrency

Silicon Valley JUG: JVM Mechanics
Silicon Valley JUG: JVM MechanicsSilicon Valley JUG: JVM Mechanics
Silicon Valley JUG: JVM MechanicsAzul Systems, Inc.
 
Fork and join framework
Fork and join frameworkFork and join framework
Fork and join frameworkMinh Tran
 
Jdk 7 4-forkjoin
Jdk 7 4-forkjoinJdk 7 4-forkjoin
Jdk 7 4-forkjoinknight1128
 
Java util concurrent
Java util concurrentJava util concurrent
Java util concurrentRoger Xia
 
Parallel Programming With Dot Net
Parallel Programming With Dot NetParallel Programming With Dot Net
Parallel Programming With Dot NetNeeraj Kaushik
 
Concurrent Programming in Java
Concurrent Programming in JavaConcurrent Programming in Java
Concurrent Programming in JavaRuben Inoto Soto
 
Core Java Programming Language (JSE) : Chapter XII - Threads
Core Java Programming Language (JSE) : Chapter XII -  ThreadsCore Java Programming Language (JSE) : Chapter XII -  Threads
Core Java Programming Language (JSE) : Chapter XII - ThreadsWebStackAcademy
 
.NET Multithreading/Multitasking
.NET Multithreading/Multitasking.NET Multithreading/Multitasking
.NET Multithreading/MultitaskingSasha Kravchuk
 
Lec7!JavaThreads.ppt
Lec7!JavaThreads.pptLec7!JavaThreads.ppt
Lec7!JavaThreads.pptssuserec53e73
 
Threads and concurrency in Java 1.5
Threads and concurrency in Java 1.5Threads and concurrency in Java 1.5
Threads and concurrency in Java 1.5Peter Antman
 
13multithreaded Programming
13multithreaded Programming13multithreaded Programming
13multithreaded ProgrammingAdil Jafri
 
Software Transactioneel Geheugen
Software Transactioneel GeheugenSoftware Transactioneel Geheugen
Software Transactioneel GeheugenDevnology
 

Semelhante a Java Concurrency (20)

Silicon Valley JUG: JVM Mechanics
Silicon Valley JUG: JVM MechanicsSilicon Valley JUG: JVM Mechanics
Silicon Valley JUG: JVM Mechanics
 
Concurrency-5.pdf
Concurrency-5.pdfConcurrency-5.pdf
Concurrency-5.pdf
 
Java Programming - 08 java threading
Java Programming - 08 java threadingJava Programming - 08 java threading
Java Programming - 08 java threading
 
Fork and join framework
Fork and join frameworkFork and join framework
Fork and join framework
 
Jdk 7 4-forkjoin
Jdk 7 4-forkjoinJdk 7 4-forkjoin
Jdk 7 4-forkjoin
 
Java util concurrent
Java util concurrentJava util concurrent
Java util concurrent
 
Parallel Programming With Dot Net
Parallel Programming With Dot NetParallel Programming With Dot Net
Parallel Programming With Dot Net
 
Lecture10
Lecture10Lecture10
Lecture10
 
Concurrent Programming in Java
Concurrent Programming in JavaConcurrent Programming in Java
Concurrent Programming in Java
 
Thread 1
Thread 1Thread 1
Thread 1
 
Core Java Programming Language (JSE) : Chapter XII - Threads
Core Java Programming Language (JSE) : Chapter XII -  ThreadsCore Java Programming Language (JSE) : Chapter XII -  Threads
Core Java Programming Language (JSE) : Chapter XII - Threads
 
.NET Multithreading/Multitasking
.NET Multithreading/Multitasking.NET Multithreading/Multitasking
.NET Multithreading/Multitasking
 
Lec7!JavaThreads.ppt
Lec7!JavaThreads.pptLec7!JavaThreads.ppt
Lec7!JavaThreads.ppt
 
Lec7!JavaThreads.ppt
Lec7!JavaThreads.pptLec7!JavaThreads.ppt
Lec7!JavaThreads.ppt
 
Multithreading in Java
Multithreading in JavaMultithreading in Java
Multithreading in Java
 
Threads and concurrency in Java 1.5
Threads and concurrency in Java 1.5Threads and concurrency in Java 1.5
Threads and concurrency in Java 1.5
 
13multithreaded Programming
13multithreaded Programming13multithreaded Programming
13multithreaded Programming
 
Software Transactioneel Geheugen
Software Transactioneel GeheugenSoftware Transactioneel Geheugen
Software Transactioneel Geheugen
 
Introduction+To+Java+Concurrency
Introduction+To+Java+ConcurrencyIntroduction+To+Java+Concurrency
Introduction+To+Java+Concurrency
 
Java adv
Java advJava adv
Java adv
 

Mais de Carol McDonald

Introduction to machine learning with GPUs
Introduction to machine learning with GPUsIntroduction to machine learning with GPUs
Introduction to machine learning with GPUsCarol McDonald
 
Streaming healthcare Data pipeline using Apache APIs: Kafka and Spark with Ma...
Streaming healthcare Data pipeline using Apache APIs: Kafka and Spark with Ma...Streaming healthcare Data pipeline using Apache APIs: Kafka and Spark with Ma...
Streaming healthcare Data pipeline using Apache APIs: Kafka and Spark with Ma...Carol McDonald
 
Analyzing Flight Delays with Apache Spark, DataFrames, GraphFrames, and MapR-DB
Analyzing Flight Delays with Apache Spark, DataFrames, GraphFrames, and MapR-DBAnalyzing Flight Delays with Apache Spark, DataFrames, GraphFrames, and MapR-DB
Analyzing Flight Delays with Apache Spark, DataFrames, GraphFrames, and MapR-DBCarol McDonald
 
Analysis of Popular Uber Locations using Apache APIs: Spark Machine Learning...
Analysis of Popular Uber Locations using Apache APIs:  Spark Machine Learning...Analysis of Popular Uber Locations using Apache APIs:  Spark Machine Learning...
Analysis of Popular Uber Locations using Apache APIs: Spark Machine Learning...Carol McDonald
 
Predicting Flight Delays with Spark Machine Learning
Predicting Flight Delays with Spark Machine LearningPredicting Flight Delays with Spark Machine Learning
Predicting Flight Delays with Spark Machine LearningCarol McDonald
 
Structured Streaming Data Pipeline Using Kafka, Spark, and MapR-DB
Structured Streaming Data Pipeline Using Kafka, Spark, and MapR-DBStructured Streaming Data Pipeline Using Kafka, Spark, and MapR-DB
Structured Streaming Data Pipeline Using Kafka, Spark, and MapR-DBCarol McDonald
 
Streaming Machine learning Distributed Pipeline for Real-Time Uber Data Using...
Streaming Machine learning Distributed Pipeline for Real-Time Uber Data Using...Streaming Machine learning Distributed Pipeline for Real-Time Uber Data Using...
Streaming Machine learning Distributed Pipeline for Real-Time Uber Data Using...Carol McDonald
 
Applying Machine Learning to IOT: End to End Distributed Pipeline for Real-Ti...
Applying Machine Learning to IOT: End to End Distributed Pipeline for Real-Ti...Applying Machine Learning to IOT: End to End Distributed Pipeline for Real-Ti...
Applying Machine Learning to IOT: End to End Distributed Pipeline for Real-Ti...Carol McDonald
 
Applying Machine Learning to IOT: End to End Distributed Pipeline for Real- T...
Applying Machine Learning to IOT: End to End Distributed Pipeline for Real- T...Applying Machine Learning to IOT: End to End Distributed Pipeline for Real- T...
Applying Machine Learning to IOT: End to End Distributed Pipeline for Real- T...Carol McDonald
 
How Big Data is Reducing Costs and Improving Outcomes in Health Care
How Big Data is Reducing Costs and Improving Outcomes in Health CareHow Big Data is Reducing Costs and Improving Outcomes in Health Care
How Big Data is Reducing Costs and Improving Outcomes in Health CareCarol McDonald
 
Demystifying AI, Machine Learning and Deep Learning
Demystifying AI, Machine Learning and Deep LearningDemystifying AI, Machine Learning and Deep Learning
Demystifying AI, Machine Learning and Deep LearningCarol McDonald
 
Applying Machine learning to IOT: End to End Distributed Distributed Pipeline...
Applying Machine learning to IOT: End to End Distributed Distributed Pipeline...Applying Machine learning to IOT: End to End Distributed Distributed Pipeline...
Applying Machine learning to IOT: End to End Distributed Distributed Pipeline...Carol McDonald
 
Streaming patterns revolutionary architectures
Streaming patterns revolutionary architectures Streaming patterns revolutionary architectures
Streaming patterns revolutionary architectures Carol McDonald
 
Spark machine learning predicting customer churn
Spark machine learning predicting customer churnSpark machine learning predicting customer churn
Spark machine learning predicting customer churnCarol McDonald
 
Fast Cars, Big Data How Streaming can help Formula 1
Fast Cars, Big Data How Streaming can help Formula 1Fast Cars, Big Data How Streaming can help Formula 1
Fast Cars, Big Data How Streaming can help Formula 1Carol McDonald
 
Applying Machine Learning to Live Patient Data
Applying Machine Learning to  Live Patient DataApplying Machine Learning to  Live Patient Data
Applying Machine Learning to Live Patient DataCarol McDonald
 
Streaming Patterns Revolutionary Architectures with the Kafka API
Streaming Patterns Revolutionary Architectures with the Kafka APIStreaming Patterns Revolutionary Architectures with the Kafka API
Streaming Patterns Revolutionary Architectures with the Kafka APICarol McDonald
 
Apache Spark Machine Learning Decision Trees
Apache Spark Machine Learning Decision TreesApache Spark Machine Learning Decision Trees
Apache Spark Machine Learning Decision TreesCarol McDonald
 
Advanced Threat Detection on Streaming Data
Advanced Threat Detection on Streaming DataAdvanced Threat Detection on Streaming Data
Advanced Threat Detection on Streaming DataCarol McDonald
 

Mais de Carol McDonald (20)

Introduction to machine learning with GPUs
Introduction to machine learning with GPUsIntroduction to machine learning with GPUs
Introduction to machine learning with GPUs
 
Streaming healthcare Data pipeline using Apache APIs: Kafka and Spark with Ma...
Streaming healthcare Data pipeline using Apache APIs: Kafka and Spark with Ma...Streaming healthcare Data pipeline using Apache APIs: Kafka and Spark with Ma...
Streaming healthcare Data pipeline using Apache APIs: Kafka and Spark with Ma...
 
Analyzing Flight Delays with Apache Spark, DataFrames, GraphFrames, and MapR-DB
Analyzing Flight Delays with Apache Spark, DataFrames, GraphFrames, and MapR-DBAnalyzing Flight Delays with Apache Spark, DataFrames, GraphFrames, and MapR-DB
Analyzing Flight Delays with Apache Spark, DataFrames, GraphFrames, and MapR-DB
 
Analysis of Popular Uber Locations using Apache APIs: Spark Machine Learning...
Analysis of Popular Uber Locations using Apache APIs:  Spark Machine Learning...Analysis of Popular Uber Locations using Apache APIs:  Spark Machine Learning...
Analysis of Popular Uber Locations using Apache APIs: Spark Machine Learning...
 
Predicting Flight Delays with Spark Machine Learning
Predicting Flight Delays with Spark Machine LearningPredicting Flight Delays with Spark Machine Learning
Predicting Flight Delays with Spark Machine Learning
 
Structured Streaming Data Pipeline Using Kafka, Spark, and MapR-DB
Structured Streaming Data Pipeline Using Kafka, Spark, and MapR-DBStructured Streaming Data Pipeline Using Kafka, Spark, and MapR-DB
Structured Streaming Data Pipeline Using Kafka, Spark, and MapR-DB
 
Streaming Machine learning Distributed Pipeline for Real-Time Uber Data Using...
Streaming Machine learning Distributed Pipeline for Real-Time Uber Data Using...Streaming Machine learning Distributed Pipeline for Real-Time Uber Data Using...
Streaming Machine learning Distributed Pipeline for Real-Time Uber Data Using...
 
Applying Machine Learning to IOT: End to End Distributed Pipeline for Real-Ti...
Applying Machine Learning to IOT: End to End Distributed Pipeline for Real-Ti...Applying Machine Learning to IOT: End to End Distributed Pipeline for Real-Ti...
Applying Machine Learning to IOT: End to End Distributed Pipeline for Real-Ti...
 
Applying Machine Learning to IOT: End to End Distributed Pipeline for Real- T...
Applying Machine Learning to IOT: End to End Distributed Pipeline for Real- T...Applying Machine Learning to IOT: End to End Distributed Pipeline for Real- T...
Applying Machine Learning to IOT: End to End Distributed Pipeline for Real- T...
 
How Big Data is Reducing Costs and Improving Outcomes in Health Care
How Big Data is Reducing Costs and Improving Outcomes in Health CareHow Big Data is Reducing Costs and Improving Outcomes in Health Care
How Big Data is Reducing Costs and Improving Outcomes in Health Care
 
Demystifying AI, Machine Learning and Deep Learning
Demystifying AI, Machine Learning and Deep LearningDemystifying AI, Machine Learning and Deep Learning
Demystifying AI, Machine Learning and Deep Learning
 
Spark graphx
Spark graphxSpark graphx
Spark graphx
 
Applying Machine learning to IOT: End to End Distributed Distributed Pipeline...
Applying Machine learning to IOT: End to End Distributed Distributed Pipeline...Applying Machine learning to IOT: End to End Distributed Distributed Pipeline...
Applying Machine learning to IOT: End to End Distributed Distributed Pipeline...
 
Streaming patterns revolutionary architectures
Streaming patterns revolutionary architectures Streaming patterns revolutionary architectures
Streaming patterns revolutionary architectures
 
Spark machine learning predicting customer churn
Spark machine learning predicting customer churnSpark machine learning predicting customer churn
Spark machine learning predicting customer churn
 
Fast Cars, Big Data How Streaming can help Formula 1
Fast Cars, Big Data How Streaming can help Formula 1Fast Cars, Big Data How Streaming can help Formula 1
Fast Cars, Big Data How Streaming can help Formula 1
 
Applying Machine Learning to Live Patient Data
Applying Machine Learning to  Live Patient DataApplying Machine Learning to  Live Patient Data
Applying Machine Learning to Live Patient Data
 
Streaming Patterns Revolutionary Architectures with the Kafka API
Streaming Patterns Revolutionary Architectures with the Kafka APIStreaming Patterns Revolutionary Architectures with the Kafka API
Streaming Patterns Revolutionary Architectures with the Kafka API
 
Apache Spark Machine Learning Decision Trees
Apache Spark Machine Learning Decision TreesApache Spark Machine Learning Decision Trees
Apache Spark Machine Learning Decision Trees
 
Advanced Threat Detection on Streaming Data
Advanced Threat Detection on Streaming DataAdvanced Threat Detection on Streaming Data
Advanced Threat Detection on Streaming Data
 

Último

H2O.ai CEO/Founder: Sri Ambati Keynote at Wells Fargo Day
H2O.ai CEO/Founder: Sri Ambati Keynote at Wells Fargo DayH2O.ai CEO/Founder: Sri Ambati Keynote at Wells Fargo Day
H2O.ai CEO/Founder: Sri Ambati Keynote at Wells Fargo DaySri Ambati
 
Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 365Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 3652toLead Limited
 
Gen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdfGen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdfAddepto
 
Streamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project SetupStreamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project SetupFlorian Wilhelm
 
Unleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding ClubUnleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding ClubKalema Edgar
 
DevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platformsDevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platformsSergiu Bodiu
 
The Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and ConsThe Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and ConsPixlogix Infotech
 
Search Engine Optimization SEO PDF for 2024.pdf
Search Engine Optimization SEO PDF for 2024.pdfSearch Engine Optimization SEO PDF for 2024.pdf
Search Engine Optimization SEO PDF for 2024.pdfRankYa
 
CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):comworks
 
"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr Bagan"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr BaganFwdays
 
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024BookNet Canada
 
Anypoint Exchange: It’s Not Just a Repo!
Anypoint Exchange: It’s Not Just a Repo!Anypoint Exchange: It’s Not Just a Repo!
Anypoint Exchange: It’s Not Just a Repo!Manik S Magar
 
Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!Commit University
 
Powerpoint exploring the locations used in television show Time Clash
Powerpoint exploring the locations used in television show Time ClashPowerpoint exploring the locations used in television show Time Clash
Powerpoint exploring the locations used in television show Time Clashcharlottematthew16
 
Take control of your SAP testing with UiPath Test Suite
Take control of your SAP testing with UiPath Test SuiteTake control of your SAP testing with UiPath Test Suite
Take control of your SAP testing with UiPath Test SuiteDianaGray10
 
SAP Build Work Zone - Overview L2-L3.pptx
SAP Build Work Zone - Overview L2-L3.pptxSAP Build Work Zone - Overview L2-L3.pptx
SAP Build Work Zone - Overview L2-L3.pptxNavinnSomaal
 
What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024Stephanie Beckett
 
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024BookNet Canada
 
Story boards and shot lists for my a level piece
Story boards and shot lists for my a level pieceStory boards and shot lists for my a level piece
Story boards and shot lists for my a level piececharlottematthew16
 

Último (20)

E-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptx
E-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptxE-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptx
E-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptx
 
H2O.ai CEO/Founder: Sri Ambati Keynote at Wells Fargo Day
H2O.ai CEO/Founder: Sri Ambati Keynote at Wells Fargo DayH2O.ai CEO/Founder: Sri Ambati Keynote at Wells Fargo Day
H2O.ai CEO/Founder: Sri Ambati Keynote at Wells Fargo Day
 
Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 365Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 365
 
Gen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdfGen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdf
 
Streamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project SetupStreamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project Setup
 
Unleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding ClubUnleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding Club
 
DevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platformsDevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platforms
 
The Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and ConsThe Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and Cons
 
Search Engine Optimization SEO PDF for 2024.pdf
Search Engine Optimization SEO PDF for 2024.pdfSearch Engine Optimization SEO PDF for 2024.pdf
Search Engine Optimization SEO PDF for 2024.pdf
 
CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):
 
"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr Bagan"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr Bagan
 
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
 
Anypoint Exchange: It’s Not Just a Repo!
Anypoint Exchange: It’s Not Just a Repo!Anypoint Exchange: It’s Not Just a Repo!
Anypoint Exchange: It’s Not Just a Repo!
 
Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!
 
Powerpoint exploring the locations used in television show Time Clash
Powerpoint exploring the locations used in television show Time ClashPowerpoint exploring the locations used in television show Time Clash
Powerpoint exploring the locations used in television show Time Clash
 
Take control of your SAP testing with UiPath Test Suite
Take control of your SAP testing with UiPath Test SuiteTake control of your SAP testing with UiPath Test Suite
Take control of your SAP testing with UiPath Test Suite
 
SAP Build Work Zone - Overview L2-L3.pptx
SAP Build Work Zone - Overview L2-L3.pptxSAP Build Work Zone - Overview L2-L3.pptx
SAP Build Work Zone - Overview L2-L3.pptx
 
What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024
 
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
 
Story boards and shot lists for my a level piece
Story boards and shot lists for my a level pieceStory boards and shot lists for my a level piece
Story boards and shot lists for my a level piece
 

Java Concurrency

  • 1.
  • 2.
  • 4.
  • 5.
  • 6.
  • 7.
  • 8.
  • 9.
  • 10.
  • 11.
  • 12.
  • 13.
  • 14.
  • 15. Executor Framework for asynchronous execution public interface Executor { void execute (Runnable command); } public interface ExecutorService extends Executor { .. } public class Executors { //Factory methods static ExecutorService newFixedThreadPool(int poolSize); ... } Executor pool = Executors.newFixedThreadPool(5); pool.execute ( runnable ) ;
  • 16.
  • 17. Thread Pool Example class WebService { public static void main(String[] args) { Executor pool = Executors.newFixedThreadPool(5); ServerSocket socket = new ServerSocket(999); for (;;) { final Socket connection = socket.accept(); Runnable task = new Runnable() { public void run() { new Handler().process ( connection ); } } pool.execute ( task ) ; } } } class Handler { void process (Socket s); }
  • 18.
  • 19.
  • 20. ScheduledExecutorService Example ScheduledExecutorService sched = Executors. newSingleThreadScheduledExecutor (); public void runTwiceAnHour(long howLong) { final Runnable rTask = new Runnable() { public void run() { /* Work to do */ } }; final ScheduledFuture<?> rTaskFuture = sched. scheduleAtFixedRate (rTask, 0, 1800, SECONDS); sched. schedule (new Runnable { public void run { rTaskFuture.cancel(true); } }, howLong, SECONDS); }
  • 21.
  • 22.
  • 23.
  • 24.
  • 25. Lock Example Lock lock = new RentrantLock(); public void accessProtectedResource() throws IllegalMonitorStateException { lock.lock(); try { // Access lock protected resource } finally { // Ensure lock is always released lock.unlock(); } }
  • 26.
  • 27. ReadWriteLock Example ReentrantReadWriteLock rwl = new ReentrantReadWriteLock (); Lock rLock = rwl.readLock (); Lock wLock = rwl.writeLock (); ArrayList<String> data = new ArrayList<String>(); public String getData(int pos) { r.lock () ; try { return data.get (pos); } finally { r.unlock (); } } public void addData(int pos, String value) { w.lock (); try { data.add (pos, value); } finally { w.unlock (); } }
  • 28.
  • 29.
  • 30.
  • 31. Blocking Queue Example: 1 private BlockingQueue<String> msgQueue ; public Logger ( BlockingQueue<String> mq) { msgQueue = mq; } public void run() { try { while (true) { String message = msgQueue.take (); /* Log message */ } } catch (InterruptedException ie) { } }
  • 32. Blocking Queue Example: 2 private ArrayBlockingQueue messageQueue = new ArrayBlockingQueue<String>(10); Logger logger = new Logger( messageQueue ); public void run() { String someMessage; try { while (true) { /* Do some processing */ /* Blocks if no space available */ messageQueue.put(someMessage) ; } } catch (InterruptedException ie) { } }
  • 33.
  • 34.
  • 37.
  • 38.
  • 39.
  • 40.
  • 41.

Notas do Editor

  1. Lets look at some of the changes and new features in the Java Virtual Machine
  2. Previously Java has supported several very primitive mechanisms for co-ordinating a number of threads. The synchronized keyword can be applied to methods or code blocks and the Thread class supports the wait, notify, sleep and interrupt mothods. The problem with these primitive mechanisms is that they are just that: primitive. As we will see the new utilities will greatly enhance Java applications in terms of scalability, performance, readability and thread safety.
  3. The idea behind the new concurrency utilities is to provide a much richer set of functions that programmers can use to create simple and powerful multi-threaded applications, in the same way that the Collections classes provided a much richer set of data structure based APIs. By providing much finer granularity of locking and different approaches such as multiple read-single write locks a secondary aim is t o enable the performance of a multi-threaded Java application to match or exceed that of native C applications in the high-end server environment. Previously Java has supported several very primitive mechanisms for co-ordinating a number of threads. The synchronized keyword can be applied to methods or code blocks and the Thread class supports the wait, notify, sleep and interrupt mothods. The problem with these primitive mechanisms is that they are just that: primitive. As we will see the new utilities will greatly enhance Java applications in terms of scalability, performance, readability and thread safety.
  4. Here is a list of things we&apos;ll talk about in this session. This is not an exhaustive list of all the new features, but given the limited time we have this should give you a good grasp of the main areas of functionality. One of the main changes in using the new concurrency utilities is the concept of moving away from interacting directly with a thread object. As we&apos;ll see the new and preferred way is through an interface called ExecutorService. There are several factory methods available to easily provide the programmer with standardised mechanisms for the Executor such as thread pools, single thread and priority threads. # Task Scheduling Framework - The Executor framework is a framework for standardizing invocation, scheduling, execution, and control of asynchronous tasks according to a set of execution policies. Implementations are provided that allow tasks to be executed within the submitting thread, in a single background thread (as with events in Swing), in a newly created thread, or in a thread pool, and developers can create of Executor supporting arbitrary execution policies. The built-in implementations offer configurable policies such as queue length limits and saturation policy which can improve the stability of applications by preventing runaway resource consumption. # Concurrent Collections - Several new Collections classes have been added, including the new Queue and BlockingQueue interfaces, and high-performance, concurrent implementations of Map, List, and Queue. Until now it has required relatively complex coding to allow a child thread to return a result to the its parent. This is even more complex when it is necessary to synchonize the threads so that the parent can only continue when the child has completed generatijng the result. This becomes very simple now through the use of Callable and Future. Semaphores are a well understood mechanism that are now supported on Java. BlockingQueues allow simple data structures to be used by multiple threads in a concurrent way such that the programmer is not responsible for ensuring safe concurrent access. Lastly the idea of an Atomic variable that can safely be accessed and modified is also iincluded in the concurrency utilities.
  5. Here is a list of things we&apos;ll talk about in this session. This is not an exhaustive list of all the new features, but given the limited time we have this should give you a good grasp of the main areas of functionality. One of the main changes in using the new concurrency utilities is the concept of moving away from interacting directly with a thread object. As we&apos;ll see the new and preferred way is through an interface called ExecutorService. There are several factory methods available to easily provide the programmer with standardised mechanisms for the Executor such as thread pools, single thread and priority threads. # Task Scheduling Framework - The Executor framework is a framework for standardizing invocation, scheduling, execution, and control of asynchronous tasks according to a set of execution policies. Implementations are provided that allow tasks to be executed within the submitting thread, in a single background thread (as with events in Swing), in a newly created thread, or in a thread pool, and developers can create of Executor supporting arbitrary execution policies. The built-in implementations offer configurable policies such as queue length limits and saturation policy which can improve the stability of applications by preventing runaway resource consumption. # Concurrent Collections - Several new Collections classes have been added, including the new Queue and BlockingQueue interfaces, and high-performance, concurrent implementations of Map, List, and Queue. Until now it has required relatively complex coding to allow a child thread to return a result to the its parent. This is even more complex when it is necessary to synchonize the threads so that the parent can only continue when the child has completed generatijng the result. This becomes very simple now through the use of Callable and Future. Semaphores are a well understood mechanism that are now supported on Java. BlockingQueues allow simple data structures to be used by multiple threads in a concurrent way such that the programmer is not responsible for ensuring safe concurrent access. Lastly the idea of an Atomic variable that can safely be accessed and modified is also iincluded in the concurrency utilities.
  6. As mentioned earlier programmers should now not interact directly with the Thread class. Before, we would create a class that implemented the Runnable interface. To start this in a new thread we would use a line like this: create a new thread with using the Runnable class and call the start method that would in turn call the run method in our class. This is still quite correct, but the idea is to replace this with an abstracted interface, Executor. Instead of calling start we call execute. Since this is abstracted away from the Thread class it becomes a simple task to change the way we handle the threading should we wish to do so at a later date. For example, we could start with a piece of code that creates a single thread to execute our new code. As requirements and processing power change we find that we need to run a number of threads for our class. We can simply change the factory method we use to create a thread pool and we are then able to use the same class in a number of threads rather than just one.
  7. Here is an example of code that uses the new Executor, Executors and ExecutorService classes. The example is a standard web service class that needs to handle a number of incoming connections simultaneously through a number of separate threads. The number of threads needs to be bounded to prevent the system from running out of resources when the load becomes too high. Previously it would have been necessary to create your own thread pooling class that would create a set of threads and then manage all of the alloaction and deallocation of those threads with all of the required concurrent access controls. With the concurrency utilities this is all provided by default. In the main routine we initialise a new fixed thread pool with a size of 7. We use the newFixedThreadPool method of the Executors class. This will return a ExecutorService object. Since ExecutorService implements the Executor interface we can assign it to an Executor object reference. To handle an incoming connection we simply call execute on our pool object passing it a Runnable object (which in this case is defined through an inner class). The run method does whatever work we need the thread to do. Whenever connections come in they will be allocates a thread from the pool. When the run method completes the thread will automatically be returned to the pool. If a connection comes in and all threads are in use the main loop will block until a thread is freed.
  8. The Lock interface provides more extensive locking operations than using a synchronized block. Because we are using methods of a class to explicitly perform the lock and unlock operations the programmer needs to be more careful in its use. With a synchronized block of code it is impossible to forget to unlock it. Once the code execution leaves that block whether normally or through some for of exception, the lock is released. Using the Lock class the programmer must typically use a try-finally construct and put the unlock call within the finally clause to ensure that the lock is always released. One advantage of the Lock interface over synchronized is the ability to not block if a lock is not available. The tryLock method will always return immediately, returning true if the lock was aquired or false if not. This method may also be called with a timeout parameter so the thread will only block for the specified time if the lock is not aquired. ReentrantLock provides a concrete implementation of the Lock interface. The thread that holds the lock can call the lock method multiple times without blocking. This is especially useful in recursive code that needs to protect access to a certain section of code.
  9. ReentrantLock provides a concrete implementation of the Lock interface. The thread that holds the lock can call the lock method multiple times without blocking. This is especially useful in recursive code that needs to protect access to a certain section of code.
  10. The ReadWriteLock permits multiple threads to have read access to a protected piece of code, but only one thread may access the code in write mode. Effectively the ReadWriteLock consists of two locks that are implemented as inner classes. If a thread aquires the read lock other threads may also aquire the read lock. If a read lock is held no thread may aquire the write lock until all read locks have been released. If a thread holds the write lock, no thread may aquire either the write lock or a read lock. ReadWriteLock is an interface. RentrantReadWriteLock is a concrete implementation of this interface.
  11. The BlockingQueue interface is a Queue that additionally supports operations that wait for the queue to become non-empty when retrieving an element, and wait for space to become available in the queue when storing an element. A BlockingQueue does not accept null elements. ArrayBlockingQueue is a concrete implementation of the BlockingQueue interface. An ArrayBlockingQueue is a bounded blocking queue backed by an array. This queue orders elements FIFO (first-in-first-out). The head of the queue is that element that has been on the queue the longest time. The tail of the queue is that element that has been on the queue the shortest time. New elements are inserted at the tail of the queue, and the queue retrieval operations obtain elements at the head of the queue. The Blocking queue provides methods to insert and remove objects from the queue (it is generic so can be typed). put() adds the specified element to the tail of this queue, waiting if necessary for space to become available. offer() inserts the specified element at the tail of this queue if possible, returning immediately if this queue is full. peek() retrieves, but does not remove, the head of this queue, returning null if this queue is empty. take() retrieves and removes the head of this queue, waiting if no elements are present on this queue. poll() retrieves and removes the head of this queue, null if this queue is empty. poll can also be specified with a time out so that the call will wait if necessary up to the specified wait time if no elements are present on this queue.
  12. Here is an example of the use of a BlockingQueue. The class implements a logger that will be used by a number of threads to record information. The constructor takes a BlockingQueue (with type argument String). In the run method messages are retrieved from the queue using the take method. When the queue is empty the logging thread will block until messages become available. Once a message is retrieved it can be logged in whichever way is required.
  13. Having defined our logging thread here is a class that uses the logger. A new ArrayBlockingQueue is instantiated with a type argument of String and a size of 10 elements. This is passed to the logger constructor as required. We can now start a number of threads that use this logger to record messages. We use the put method on the messageQueue. If the queue is full the thread will block until the logger has removed messages. The BlockingQueue will handle contention in a thread safe way should multiple threads be waiting for space to become available in the queue.