SlideShare a Scribd company logo
1 of 19
SivaramaSundar.D
29th Nov 2012
 Concepts
 When & Why do we need threads
 Threads in java
 Concurrency: Thread control & Synchronization
 Concurrency: Data management between threads
 Best practices: Threading the right way;
 Q&A
 Processes
 A Process has a self-contained execution environment; an application, in general terms – with own
memory address space; with a main execution thread; which can own O/S resource handles – files,
sockets etc.
 1..* threads; Each process has one Main thread;
 System threads – GC, Object finalization, JVM housekeeping
 Timers and User created threads
 Threads
 Execution unit – to execute a sequence of instructions
 Owns: Stack, Program Counter, Local variables
 Shares: Memory, Filehandles, Process States
 ThreadGroups
 Grouping threads into a logical collection; Not used much.
 ThreadPools
 A thread pool is a collection of threads set aside for a specific task; Ex: webserver thread pool; saves
thread creation overheads everytime;
 execute(Runnable command)
 Used for executing large numbers of asynchronous tasks
 provide a boundary mechanism to create and managing the resources within the pool
 Better thread management; Cleaner shutdown of threads;
 Ability to Add, Remove, Enumerate future tasks; Apt for a scheduler;
 Multitasking – Receive data via a socket & write to file(s)
 A Server handling multiple concurrent requests to serve data
 Make the UI more responsive
 Number crunching; Bulk data processing;
 Take advantage of multiprocessor systems
 Simplify program logic when there are multiple independent
entities
 Perform blocking I/O without blocking the entire program
 Ex:
 A Webserver
 A real time device monitor to display device parameters
 A Monitoring application, polling multiple sources & providing live
updates
 Runnable Interface & Thread Class, Daemon threads
 Instantiate the “Thread” Class with a “Runnable” implementation
(preferred way!)
 Subclass the “Thread” class & override the “run” method
 Start – begin execution
 setDaemon – thread will be terminated
by VM during shutdown;
normal threads won’t;
 sleep
 Sleeps are not precise;
 Sleep either in ms or ns
 The Sleep can be interrupted,
by other threads via the thread.interrupt call
 Yield (rarely used) - Relinquish control ;
during long running operations;
 Interrupt
 Interrupts the wait state of the thread; invoked by the thread owner;
 Raises a InterruptedException
 Join
 Makes the calling thread wait until other thread completes;
 Typical usage: make sure all the child threads are terminated;
 Can be interrupted by the thread.interrupt call
 wait
 Notify – Wakes up the thread waiting on the given object’s
monitor
 notifyAll – Wakes up all the threads waiting on the given
object’s monitor
 Obselete methods
 suspend
 resume
 Stop – use internal flags, join, wait & interrupt mechanisms
instead
 Timers, TimerTask (Daemon)
 Schedule tasks (Runnable) for future execution in a
background thread. Tasks may be scheduled for one-time
execution, or for repeated execution at regular intervals
 Schedule (task, delay)
 ThreadFactory
 Help create threads of a given type; subclassed threads
 ThreadInfo
 Contains the information about a thread
 ThreadReference
 Object ref. with additional access to thread-specific
information from the target VM. Provides access to internal
stack frames, monitor references.
 Why Synchronization
 Prevent shared data corruption / thread interference / data integrity
 Code
 Locks (Monitors)- Synchronized, Volatile
 Each object in java has a unique monitor.
When a synchronized method / block is invoked by the thread,
the thread tries to take ownership of the monitor or block until it
gets the ownership;
The Thread acquires the monitor for the given object
(ex:this / method, class object ref.). A monitor is automatically
released when the method / block execution completes.
 Only one thread at a time
can own an object's monitor.
 Synchronized
 Protect Code & Make data changes visible
 Block level
 Method level (uses intrinsic lock of the method’s object instance)
 Volatile – bypass processer cache to use main memory
 One thread – One Lock – anytime
 Locks will be released in the event of any uncaught exceptions
 Lock Interface for better control than “Synchronized”
 A single Lock can have multiple Conditions
 ReentrantLock – lock() ; Try... Finally{ unlock(); }
 ReentrantReadWriteLock - to get a read / write or both locks
 Data
 Semaphores– Semaphore (Counting Semaphore)
 acquire(), release()
 Mechanism to control access to a pool of shared resource, between
multiple processes, threads
 Acts like a gate – for a limited access pool / lift – with a fixed
capacity; some threads have to yield control, for the other threads to
access the shared data;
 While Locks are exclusive, semaphores are not
 Other examples:
 Fixed no. of meeting rooms – with controlled access
 Mutexes – Same as a binary semaphore (lock - yes/no), but
across processes
 Normally mutexes has owners
 Typical usage – to ensure single instance of an application / process
 ThreadLocal<T>
 Provide Local variables for the thread (can be accessed only within this thread)
 Each thread holds an implicit reference to its copy of a thread-local variable as long as the thread is alive
 When a thread dies; the thread local variables are subject to GC
 Java.utils.concurrent
 ThreadPoolExecutor, ScheduledThreadPoolExecutor
 Java.util.Collections classes with built in support for handling concurrency & access from multiple
threads; uses collection segmentation & hence supports non-blocking – ex: the whole collection
is not locked;
 ConcurrentHashMap
 ConcurrentLinkedDeque
 ConcurrentLinkedQueue
 ConcurrentSkipListMap
 ConcurrentSkipListSet
 Make normal collections thread safe via - java.util.Collections methods;
blocking – ex: whole collection is locked;
 SynchronousQueue
 SynchronizedCollection
 SynchronizedSet
 SynchronizedList
 SynchronizedMap
 SynchronizedSortedSet
 SynchronizedSortedMap
 Deadlock
 T1 -> W1; T1.DoSomething waits for W2.
 T2 -> W2; T2.DoSomething waits for W1.
 Hard to debug – but jConsole, jStack helps (demo with
jConsole);
 Simplify locks / avoid arbitrary synchronization
 Race Condition
 A race condition occurs when 2 or more threads access shared data and
they try to change it at the same time;
 problems occur when one thread does a "check-then-act" and another
thread does something to the value in between the "check" and the
"act“;
tip: avoid ‘check & act’
situations when using threading;
 White-boarding & Brainstorming
 Document / Comment all threading code; Be Aware of the synchronized keyword used as
part of the method name – it is easy to miss if that a synchronized method uses an
intrinsic lock; synchronized blocks are easier to spot;
 Thorough Code Reviews
 Use locks judiciously – lock while writes
 Wait for spawned threads to complete, or force stop
 Exception handling – a thread will terminate on an unhandled exception
Make use of Thread.setDefaultUncaughtExceptionHandler -handler for all threads in the VM
or
setUncaughtExceptionHandler(Thread.UncaughtExceptionHandler eh) - handler for single specific
thread
 Use immutable classes – Ex: String, Integer, BigDecimal, as they make concurrency
handling simple
 Know when JVM performs the synchronization for you: Static Initializer, final fields,
Creating objects before threads
 Avoid nested locks; to prevent deadlocks;
 Don't invoke methods on other objects while holding a lock. (Sounds crazy; )
 Ensure that when you acquire multiple locks, you always acquire the locks in
the same order in all threads.
 Keep the synchronized blocks as short as possible;
 Don’t use blocking code inside a synchronized block – ex: Inputstream.read()
 Don’t tamper thread priorities; leave it to the JVM & O/S
 Avoid starvation of resources; Don’t code long running threads;
 Aids in debugging threading issues:
 Thread.holdsLock (Object lockObj)- true if lock is held
 Thread.dumpStack()
 Inspect using Thread.State / getState()
 Provide a thread name when creating a thread
 Logs – with thread id’s;
 ThreadInfo class
 Threaddumps - Provide a stack trace of all running threads
 (tool from jdk) jstack <pid> >> threaddumps.log
 (alternate) use jConsole to monitor the jvm & analyze stack trace of all live threads
 Using the “SendSignal.exe” to send a “break” signal to the process to get a thread dump
 Threading explained in simple terms-
http://www.tutorialspoint.com/java/java_multithreading.htm
http://www.tutorialspoint.com/java/java_thread_synchronization.htm
http://www.tutorialspoint.com/java/java_multithreading.htm
http://www.tutorialspoint.com/java/java_thread_communication.htm
http://www.tutorialspoint.com/java/java_thread_deadlock.htm
 Java Concurrency in Practice – Book – www.Jcip.net
 Hardcode multi-threading in java -
http://conferences.embarcadero.com/article/32141
 Analyzing thread dumps-
http://www.javacodegeeks.com/2012/03/jvm-how-to-analyze-thread-
dump.html
 ThreadApp.java
 SimpleJavaThread.java
 Deadlock.java
 A.java
 B.java
 NewThread.java
 SuspendResume.java
 Pool.java
Threading in java - a pragmatic primer

More Related Content

What's hot

Synchronization.37
Synchronization.37Synchronization.37
Synchronization.37myrajendra
 
Multithreading In Java
Multithreading In JavaMultithreading In Java
Multithreading In Javaparag
 
[Java concurrency]02.basic thread synchronization
[Java concurrency]02.basic thread synchronization[Java concurrency]02.basic thread synchronization
[Java concurrency]02.basic thread synchronizationxuehan zhu
 
Inter threadcommunication.38
Inter threadcommunication.38Inter threadcommunication.38
Inter threadcommunication.38myrajendra
 
Programming with Threads in Java
Programming with Threads in JavaProgramming with Threads in Java
Programming with Threads in Javakoji lin
 
[Java concurrency]01.thread management
[Java concurrency]01.thread management[Java concurrency]01.thread management
[Java concurrency]01.thread managementxuehan zhu
 
Java Concurrency in Practice
Java Concurrency in PracticeJava Concurrency in Practice
Java Concurrency in PracticeAlina Dolgikh
 
Basic of Multithreading in JAva
Basic of Multithreading in JAvaBasic of Multithreading in JAva
Basic of Multithreading in JAvasuraj pandey
 
Java Multithreading Using Executors Framework
Java Multithreading Using Executors FrameworkJava Multithreading Using Executors Framework
Java Multithreading Using Executors FrameworkArun Mehra
 
Java New Evolution
Java New EvolutionJava New Evolution
Java New EvolutionAllan Huang
 
Multithreading in java
Multithreading in javaMultithreading in java
Multithreading in javaArafat Hossan
 
Multithreading in-java
Multithreading in-javaMultithreading in-java
Multithreading in-javaaalipalh
 
Lecture 23-24.pptx
Lecture 23-24.pptxLecture 23-24.pptx
Lecture 23-24.pptxtalha ijaz
 

What's hot (20)

Multi threading
Multi threadingMulti threading
Multi threading
 
Multithreading in Java
Multithreading in JavaMultithreading in Java
Multithreading in Java
 
Synchronization.37
Synchronization.37Synchronization.37
Synchronization.37
 
Multithreading In Java
Multithreading In JavaMultithreading In Java
Multithreading In Java
 
[Java concurrency]02.basic thread synchronization
[Java concurrency]02.basic thread synchronization[Java concurrency]02.basic thread synchronization
[Java concurrency]02.basic thread synchronization
 
Inter threadcommunication.38
Inter threadcommunication.38Inter threadcommunication.38
Inter threadcommunication.38
 
Programming with Threads in Java
Programming with Threads in JavaProgramming with Threads in Java
Programming with Threads in Java
 
[Java concurrency]01.thread management
[Java concurrency]01.thread management[Java concurrency]01.thread management
[Java concurrency]01.thread management
 
Java Concurrency in Practice
Java Concurrency in PracticeJava Concurrency in Practice
Java Concurrency in Practice
 
Java tips
Java tipsJava tips
Java tips
 
Basic of Multithreading in JAva
Basic of Multithreading in JAvaBasic of Multithreading in JAva
Basic of Multithreading in JAva
 
Thread
ThreadThread
Thread
 
Java Multithreading Using Executors Framework
Java Multithreading Using Executors FrameworkJava Multithreading Using Executors Framework
Java Multithreading Using Executors Framework
 
Java New Evolution
Java New EvolutionJava New Evolution
Java New Evolution
 
Threads in Java
Threads in JavaThreads in Java
Threads in Java
 
Java unit 12
Java unit 12Java unit 12
Java unit 12
 
Multithreading in java
Multithreading in javaMultithreading in java
Multithreading in java
 
Multithreading in-java
Multithreading in-javaMultithreading in-java
Multithreading in-java
 
Java Multithreading
Java MultithreadingJava Multithreading
Java Multithreading
 
Lecture 23-24.pptx
Lecture 23-24.pptxLecture 23-24.pptx
Lecture 23-24.pptx
 

Viewers also liked

Viewers also liked (18)

Jacob Jean resume
Jacob Jean resumeJacob Jean resume
Jacob Jean resume
 
E SUNDARATHEVAN RESUME
E SUNDARATHEVAN RESUMEE SUNDARATHEVAN RESUME
E SUNDARATHEVAN RESUME
 
sda.wm
sda.wmsda.wm
sda.wm
 
Anirban Das_BE-NIT_MBA-Symbiosis
Anirban Das_BE-NIT_MBA-SymbiosisAnirban Das_BE-NIT_MBA-Symbiosis
Anirban Das_BE-NIT_MBA-Symbiosis
 
Jenin Thomas-CV
Jenin Thomas-CVJenin Thomas-CV
Jenin Thomas-CV
 
CV__SD_13-12-2014
CV__SD_13-12-2014CV__SD_13-12-2014
CV__SD_13-12-2014
 
jugal update cv
jugal update cvjugal update cv
jugal update cv
 
Subbu_WM
Subbu_WMSubbu_WM
Subbu_WM
 
Snehal Mutalik - Resume
Snehal Mutalik - ResumeSnehal Mutalik - Resume
Snehal Mutalik - Resume
 
Software Open Source
Software Open SourceSoftware Open Source
Software Open Source
 
David A Shattles Resume 2015-11
David A Shattles Resume 2015-11David A Shattles Resume 2015-11
David A Shattles Resume 2015-11
 
AmrendraKumarVerma_Resume
AmrendraKumarVerma_ResumeAmrendraKumarVerma_Resume
AmrendraKumarVerma_Resume
 
DianaTChua
DianaTChuaDianaTChua
DianaTChua
 
Prem sai resume
Prem sai resumePrem sai resume
Prem sai resume
 
Juilee s kulkarni
Juilee s  kulkarniJuilee s  kulkarni
Juilee s kulkarni
 
Resume_satish_kumar_reddy
Resume_satish_kumar_reddyResume_satish_kumar_reddy
Resume_satish_kumar_reddy
 
Resume (1)
Resume (1)Resume (1)
Resume (1)
 
Job
JobJob
Job
 

Similar to Threading in java - a pragmatic primer

Concurrency with java
Concurrency with javaConcurrency with java
Concurrency with javaLuis Goldster
 
Concurrency with java
Concurrency with javaConcurrency with java
Concurrency with javaHarry Potter
 
Concurrency with java
Concurrency with javaConcurrency with java
Concurrency with javaYoung Alista
 
Concurrency with java
Concurrency with javaConcurrency with java
Concurrency with javaTony Nguyen
 
Concurrency with java
Concurrency with javaConcurrency with java
Concurrency with javaFraboni Ec
 
Concurrency with java
Concurrency with javaConcurrency with java
Concurrency with javaHoang Nguyen
 
Concurrency with java
Concurrency with javaConcurrency with java
Concurrency with javaJames Wong
 
econtent thread in java.pptx
econtent thread in java.pptxecontent thread in java.pptx
econtent thread in java.pptxramyan49
 
Multithreading Presentation
Multithreading PresentationMultithreading Presentation
Multithreading PresentationNeeraj Kaushik
 
Thread Dump Analysis
Thread Dump AnalysisThread Dump Analysis
Thread Dump AnalysisDmitry Buzdin
 
Profiler Guided Java Performance Tuning
Profiler Guided Java Performance TuningProfiler Guided Java Performance Tuning
Profiler Guided Java Performance Tuningosa_ora
 
Java multithreading
Java multithreadingJava multithreading
Java multithreadingMohammed625
 
Java Multithreading
Java MultithreadingJava Multithreading
Java MultithreadingRajkattamuri
 

Similar to Threading in java - a pragmatic primer (20)

Multithreading in java
Multithreading in javaMultithreading in java
Multithreading in java
 
Concurrency
ConcurrencyConcurrency
Concurrency
 
Java threading
Java threadingJava threading
Java threading
 
Concurrency with java
Concurrency with javaConcurrency with java
Concurrency with java
 
Concurrency with java
Concurrency with javaConcurrency with java
Concurrency with java
 
Concurrency with java
Concurrency with javaConcurrency with java
Concurrency with java
 
Concurrency with java
Concurrency with javaConcurrency with java
Concurrency with java
 
Concurrency with java
Concurrency with javaConcurrency with java
Concurrency with java
 
Concurrency with java
Concurrency with javaConcurrency with java
Concurrency with java
 
Concurrency with java
Concurrency with javaConcurrency with java
Concurrency with java
 
econtent thread in java.pptx
econtent thread in java.pptxecontent thread in java.pptx
econtent thread in java.pptx
 
Multithreading Presentation
Multithreading PresentationMultithreading Presentation
Multithreading Presentation
 
Java
JavaJava
Java
 
Thread Dump Analysis
Thread Dump AnalysisThread Dump Analysis
Thread Dump Analysis
 
Profiler Guided Java Performance Tuning
Profiler Guided Java Performance TuningProfiler Guided Java Performance Tuning
Profiler Guided Java Performance Tuning
 
multithreading
multithreadingmultithreading
multithreading
 
Java
JavaJava
Java
 
Java multithreading
Java multithreadingJava multithreading
Java multithreading
 
Java Multithreading
Java MultithreadingJava Multithreading
Java Multithreading
 
Thread
ThreadThread
Thread
 

Recently uploaded

Beyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry InnovationBeyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry InnovationSafe Software
 
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
 
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...Patryk Bandurski
 
Enhancing Worker Digital Experience: A Hands-on Workshop for Partners
Enhancing Worker Digital Experience: A Hands-on Workshop for PartnersEnhancing Worker Digital Experience: A Hands-on Workshop for Partners
Enhancing Worker Digital Experience: A Hands-on Workshop for PartnersThousandEyes
 
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024BookNet Canada
 
costume and set research powerpoint presentation
costume and set research powerpoint presentationcostume and set research powerpoint presentation
costume and set research powerpoint presentationphoebematthew05
 
Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024Scott Keck-Warren
 
Snow Chain-Integrated Tire for a Safe Drive on Winter Roads
Snow Chain-Integrated Tire for a Safe Drive on Winter RoadsSnow Chain-Integrated Tire for a Safe Drive on Winter Roads
Snow Chain-Integrated Tire for a Safe Drive on Winter RoadsHyundai Motor Group
 
Install Stable Diffusion in windows machine
Install Stable Diffusion in windows machineInstall Stable Diffusion in windows machine
Install Stable Diffusion in windows machinePadma Pradeep
 
Making_way_through_DLL_hollowing_inspite_of_CFG_by_Debjeet Banerjee.pptx
Making_way_through_DLL_hollowing_inspite_of_CFG_by_Debjeet Banerjee.pptxMaking_way_through_DLL_hollowing_inspite_of_CFG_by_Debjeet Banerjee.pptx
Making_way_through_DLL_hollowing_inspite_of_CFG_by_Debjeet Banerjee.pptxnull - The Open Security Community
 
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmaticsKotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmaticscarlostorres15106
 
CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):comworks
 
Designing IA for AI - Information Architecture Conference 2024
Designing IA for AI - Information Architecture Conference 2024Designing IA for AI - Information Architecture Conference 2024
Designing IA for AI - Information Architecture Conference 2024Enterprise Knowledge
 
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 3652toLead Limited
 
Artificial intelligence in the post-deep learning era
Artificial intelligence in the post-deep learning eraArtificial intelligence in the post-deep learning era
Artificial intelligence in the post-deep learning eraDeakin University
 
Benefits Of Flutter Compared To Other Frameworks
Benefits Of Flutter Compared To Other FrameworksBenefits Of Flutter Compared To Other Frameworks
Benefits Of Flutter Compared To Other FrameworksSoftradix Technologies
 
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks..."LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...Fwdays
 
Swan(sea) Song – personal research during my six years at Swansea ... and bey...
Swan(sea) Song – personal research during my six years at Swansea ... and bey...Swan(sea) Song – personal research during my six years at Swansea ... and bey...
Swan(sea) Song – personal research during my six years at Swansea ... and bey...Alan Dix
 
Bun (KitWorks Team Study 노별마루 발표 2024.4.22)
Bun (KitWorks Team Study 노별마루 발표 2024.4.22)Bun (KitWorks Team Study 노별마루 발표 2024.4.22)
Bun (KitWorks Team Study 노별마루 발표 2024.4.22)Wonjun Hwang
 

Recently uploaded (20)

Beyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry InnovationBeyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
 
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
 
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
 
Enhancing Worker Digital Experience: A Hands-on Workshop for Partners
Enhancing Worker Digital Experience: A Hands-on Workshop for PartnersEnhancing Worker Digital Experience: A Hands-on Workshop for Partners
Enhancing Worker Digital Experience: A Hands-on Workshop for Partners
 
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
 
costume and set research powerpoint presentation
costume and set research powerpoint presentationcostume and set research powerpoint presentation
costume and set research powerpoint presentation
 
Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024
 
Snow Chain-Integrated Tire for a Safe Drive on Winter Roads
Snow Chain-Integrated Tire for a Safe Drive on Winter RoadsSnow Chain-Integrated Tire for a Safe Drive on Winter Roads
Snow Chain-Integrated Tire for a Safe Drive on Winter Roads
 
Install Stable Diffusion in windows machine
Install Stable Diffusion in windows machineInstall Stable Diffusion in windows machine
Install Stable Diffusion in windows machine
 
Making_way_through_DLL_hollowing_inspite_of_CFG_by_Debjeet Banerjee.pptx
Making_way_through_DLL_hollowing_inspite_of_CFG_by_Debjeet Banerjee.pptxMaking_way_through_DLL_hollowing_inspite_of_CFG_by_Debjeet Banerjee.pptx
Making_way_through_DLL_hollowing_inspite_of_CFG_by_Debjeet Banerjee.pptx
 
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmaticsKotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
 
CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):
 
Designing IA for AI - Information Architecture Conference 2024
Designing IA for AI - Information Architecture Conference 2024Designing IA for AI - Information Architecture Conference 2024
Designing IA for AI - Information Architecture Conference 2024
 
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
 
Artificial intelligence in the post-deep learning era
Artificial intelligence in the post-deep learning eraArtificial intelligence in the post-deep learning era
Artificial intelligence in the post-deep learning era
 
Benefits Of Flutter Compared To Other Frameworks
Benefits Of Flutter Compared To Other FrameworksBenefits Of Flutter Compared To Other Frameworks
Benefits Of Flutter Compared To Other Frameworks
 
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks..."LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
 
The transition to renewables in India.pdf
The transition to renewables in India.pdfThe transition to renewables in India.pdf
The transition to renewables in India.pdf
 
Swan(sea) Song – personal research during my six years at Swansea ... and bey...
Swan(sea) Song – personal research during my six years at Swansea ... and bey...Swan(sea) Song – personal research during my six years at Swansea ... and bey...
Swan(sea) Song – personal research during my six years at Swansea ... and bey...
 
Bun (KitWorks Team Study 노별마루 발표 2024.4.22)
Bun (KitWorks Team Study 노별마루 발표 2024.4.22)Bun (KitWorks Team Study 노별마루 발표 2024.4.22)
Bun (KitWorks Team Study 노별마루 발표 2024.4.22)
 

Threading in java - a pragmatic primer

  • 2.  Concepts  When & Why do we need threads  Threads in java  Concurrency: Thread control & Synchronization  Concurrency: Data management between threads  Best practices: Threading the right way;  Q&A
  • 3.  Processes  A Process has a self-contained execution environment; an application, in general terms – with own memory address space; with a main execution thread; which can own O/S resource handles – files, sockets etc.  1..* threads; Each process has one Main thread;  System threads – GC, Object finalization, JVM housekeeping  Timers and User created threads  Threads  Execution unit – to execute a sequence of instructions  Owns: Stack, Program Counter, Local variables  Shares: Memory, Filehandles, Process States  ThreadGroups  Grouping threads into a logical collection; Not used much.  ThreadPools  A thread pool is a collection of threads set aside for a specific task; Ex: webserver thread pool; saves thread creation overheads everytime;  execute(Runnable command)  Used for executing large numbers of asynchronous tasks  provide a boundary mechanism to create and managing the resources within the pool  Better thread management; Cleaner shutdown of threads;  Ability to Add, Remove, Enumerate future tasks; Apt for a scheduler;
  • 4.  Multitasking – Receive data via a socket & write to file(s)  A Server handling multiple concurrent requests to serve data  Make the UI more responsive  Number crunching; Bulk data processing;  Take advantage of multiprocessor systems  Simplify program logic when there are multiple independent entities  Perform blocking I/O without blocking the entire program  Ex:  A Webserver  A real time device monitor to display device parameters  A Monitoring application, polling multiple sources & providing live updates
  • 5.
  • 6.
  • 7.  Runnable Interface & Thread Class, Daemon threads  Instantiate the “Thread” Class with a “Runnable” implementation (preferred way!)  Subclass the “Thread” class & override the “run” method  Start – begin execution  setDaemon – thread will be terminated by VM during shutdown; normal threads won’t;  sleep  Sleeps are not precise;  Sleep either in ms or ns  The Sleep can be interrupted, by other threads via the thread.interrupt call  Yield (rarely used) - Relinquish control ; during long running operations;  Interrupt  Interrupts the wait state of the thread; invoked by the thread owner;  Raises a InterruptedException
  • 8.  Join  Makes the calling thread wait until other thread completes;  Typical usage: make sure all the child threads are terminated;  Can be interrupted by the thread.interrupt call  wait  Notify – Wakes up the thread waiting on the given object’s monitor  notifyAll – Wakes up all the threads waiting on the given object’s monitor  Obselete methods  suspend  resume  Stop – use internal flags, join, wait & interrupt mechanisms instead
  • 9.  Timers, TimerTask (Daemon)  Schedule tasks (Runnable) for future execution in a background thread. Tasks may be scheduled for one-time execution, or for repeated execution at regular intervals  Schedule (task, delay)  ThreadFactory  Help create threads of a given type; subclassed threads  ThreadInfo  Contains the information about a thread  ThreadReference  Object ref. with additional access to thread-specific information from the target VM. Provides access to internal stack frames, monitor references.
  • 10.  Why Synchronization  Prevent shared data corruption / thread interference / data integrity  Code  Locks (Monitors)- Synchronized, Volatile  Each object in java has a unique monitor. When a synchronized method / block is invoked by the thread, the thread tries to take ownership of the monitor or block until it gets the ownership; The Thread acquires the monitor for the given object (ex:this / method, class object ref.). A monitor is automatically released when the method / block execution completes.  Only one thread at a time can own an object's monitor.  Synchronized  Protect Code & Make data changes visible  Block level  Method level (uses intrinsic lock of the method’s object instance)  Volatile – bypass processer cache to use main memory  One thread – One Lock – anytime  Locks will be released in the event of any uncaught exceptions  Lock Interface for better control than “Synchronized”  A single Lock can have multiple Conditions  ReentrantLock – lock() ; Try... Finally{ unlock(); }  ReentrantReadWriteLock - to get a read / write or both locks
  • 11.
  • 12.  Data  Semaphores– Semaphore (Counting Semaphore)  acquire(), release()  Mechanism to control access to a pool of shared resource, between multiple processes, threads  Acts like a gate – for a limited access pool / lift – with a fixed capacity; some threads have to yield control, for the other threads to access the shared data;  While Locks are exclusive, semaphores are not  Other examples:  Fixed no. of meeting rooms – with controlled access  Mutexes – Same as a binary semaphore (lock - yes/no), but across processes  Normally mutexes has owners  Typical usage – to ensure single instance of an application / process
  • 13.  ThreadLocal<T>  Provide Local variables for the thread (can be accessed only within this thread)  Each thread holds an implicit reference to its copy of a thread-local variable as long as the thread is alive  When a thread dies; the thread local variables are subject to GC  Java.utils.concurrent  ThreadPoolExecutor, ScheduledThreadPoolExecutor  Java.util.Collections classes with built in support for handling concurrency & access from multiple threads; uses collection segmentation & hence supports non-blocking – ex: the whole collection is not locked;  ConcurrentHashMap  ConcurrentLinkedDeque  ConcurrentLinkedQueue  ConcurrentSkipListMap  ConcurrentSkipListSet  Make normal collections thread safe via - java.util.Collections methods; blocking – ex: whole collection is locked;  SynchronousQueue  SynchronizedCollection  SynchronizedSet  SynchronizedList  SynchronizedMap  SynchronizedSortedSet  SynchronizedSortedMap
  • 14.  Deadlock  T1 -> W1; T1.DoSomething waits for W2.  T2 -> W2; T2.DoSomething waits for W1.  Hard to debug – but jConsole, jStack helps (demo with jConsole);  Simplify locks / avoid arbitrary synchronization  Race Condition  A race condition occurs when 2 or more threads access shared data and they try to change it at the same time;  problems occur when one thread does a "check-then-act" and another thread does something to the value in between the "check" and the "act“; tip: avoid ‘check & act’ situations when using threading;
  • 15.  White-boarding & Brainstorming  Document / Comment all threading code; Be Aware of the synchronized keyword used as part of the method name – it is easy to miss if that a synchronized method uses an intrinsic lock; synchronized blocks are easier to spot;  Thorough Code Reviews  Use locks judiciously – lock while writes  Wait for spawned threads to complete, or force stop  Exception handling – a thread will terminate on an unhandled exception Make use of Thread.setDefaultUncaughtExceptionHandler -handler for all threads in the VM or setUncaughtExceptionHandler(Thread.UncaughtExceptionHandler eh) - handler for single specific thread  Use immutable classes – Ex: String, Integer, BigDecimal, as they make concurrency handling simple  Know when JVM performs the synchronization for you: Static Initializer, final fields, Creating objects before threads  Avoid nested locks; to prevent deadlocks;
  • 16.  Don't invoke methods on other objects while holding a lock. (Sounds crazy; )  Ensure that when you acquire multiple locks, you always acquire the locks in the same order in all threads.  Keep the synchronized blocks as short as possible;  Don’t use blocking code inside a synchronized block – ex: Inputstream.read()  Don’t tamper thread priorities; leave it to the JVM & O/S  Avoid starvation of resources; Don’t code long running threads;  Aids in debugging threading issues:  Thread.holdsLock (Object lockObj)- true if lock is held  Thread.dumpStack()  Inspect using Thread.State / getState()  Provide a thread name when creating a thread  Logs – with thread id’s;  ThreadInfo class  Threaddumps - Provide a stack trace of all running threads  (tool from jdk) jstack <pid> >> threaddumps.log  (alternate) use jConsole to monitor the jvm & analyze stack trace of all live threads  Using the “SendSignal.exe” to send a “break” signal to the process to get a thread dump
  • 17.  Threading explained in simple terms- http://www.tutorialspoint.com/java/java_multithreading.htm http://www.tutorialspoint.com/java/java_thread_synchronization.htm http://www.tutorialspoint.com/java/java_multithreading.htm http://www.tutorialspoint.com/java/java_thread_communication.htm http://www.tutorialspoint.com/java/java_thread_deadlock.htm  Java Concurrency in Practice – Book – www.Jcip.net  Hardcode multi-threading in java - http://conferences.embarcadero.com/article/32141  Analyzing thread dumps- http://www.javacodegeeks.com/2012/03/jvm-how-to-analyze-thread- dump.html
  • 18.  ThreadApp.java  SimpleJavaThread.java  Deadlock.java  A.java  B.java  NewThread.java  SuspendResume.java  Pool.java

Editor's Notes

  1. Pub-Sub messaging Multiple devices sending updates to a UI A Logging service / Common logging component in a huge system, which gets log messages from all other subsystems and persists them via a single thread; ---------- For simple background tasks; simple threads suffice For above options, all the synchronizations mechanisms are needed
  2. Ex: Apache web-server, with a configurable thread pool, where in threads shall be pre-created and new threads created only when the number of requests become higher and cannot be served by the present pool