SlideShare a Scribd company logo
1 of 16
Download to read offline
Java course - IAG0040




               Threads &
              Concurrency



Anton Keks                           2011
Introduction to Threads
 ●
     A Thread is a lightweight process
 ●
     A Thread is a single sequential flow of control
     within a program




                                                         A Program
                        A Program




Java course – IAG0040                                  Lecture 10
Anton Keks                                                 Slide 2
More formal definition
 ●
     A thread is pure activity, i.e. the information
     about the current position of execution
     (instruction pointer), the registers and the
     current stack
 ●
     An address space is a range of addressable
     memory that is only accessible by activities
     that are allowed to read/write from it
 ●   A process consists of an address space and one
     or multiple threads

Java course – IAG0040                          Lecture 10
Anton Keks                                         Slide 3
Threads & Java
 ●
     Java supports Threads and synchronization natively
 ●
     Threads can be used for doing two or more tasks at
     once
 ●
     main() method is always executed in the “main”
     thread
     –   there are always several more system threads running
         in your Java program, e.g. garbage collector
 ●
     You can always start as many new threads as your
     program needs using the Thread class


Java course – IAG0040                                  Lecture 10
Anton Keks                                                 Slide 4
Thread class
 ●   Threads run Runnable tasks, there are two possible implementations
      –   extend the Thread class itself, overriding the run method:
          class MegaThread extends Thread { ... }
          Thread t = new MegaThread();
      –   implement the Runnable interface and pass it to a new Thread:
          class MegaRunnable implements Runnable { ... }
          Thread t = new Thread(new MegaRunnable());
 ●   Every Thread has a name: it can be specified on creation or using
     the setName() method
 ●
     Thread class provides some useful static methods:
      –   currentThread() returns the current Thread's instance
      –   sleep() pauses the current Thread for the given time
      –   yield() allows other Threads to run by pausing the current one
Java course – IAG0040                                                Lecture 10
Anton Keks                                                               Slide 5
Thread class (cont)
 ●   start() starts the new Thread in the background, note:
     run() method doesn't start the Thread!
 ●   join() waits for another Thread to die
 ●   setDaemon(true) sets the daemon flag. JVM terminates if
     there are only daemon threads left running.
 ●   getId() returns a unique Id (long) of the Thread
 ●   isAlive() tests if the Thread is alive (started and not dead)
 ●   getState() provides more information on the state
 ●   There are many other interesting is/get methods, see
     Javadoc

Java course – IAG0040                                      Lecture 10
Anton Keks                                                     Slide 6
Exception handling
 ●
     Each thread has a default top-level exception
     handler
           –   that calls printStackTrace()
 ●   Just like the main thread, where the main()
     method is executed
 ●
     If an exception is thrown out of a thread,
     the thread is terminated



Java course – IAG0040                             Lecture 10
Anton Keks                                            Slide 7
Interrupting Threads
 ●
     There are many deprecated methods in the Thread class, which
     have been proved to be dangerous (may cause deadlocks, etc):
     suspend(), resume(), stop(), destroy(), etc
 ●   Instead, interrupt() can be used
     –   it interrupts blocking/waiting method calls, e.g. sleep(),
         wait(), join(), etc, with an InterruptedException
     –   it signals the Thread that it should terminate
          ●
              interrupted flag can be checked using either the static
              Thread.interrupted() or isInterrupted() method
     –   it is a safe and graceful way to interrupt a Thread, because it
         involves interaction from the Thread itself

Java course – IAG0040                                         Lecture 10
Anton Keks                                                        Slide 8
Scheduling
●
     Scheduling is execution of multiple threads on a single CPU,
     dividing available CPU time into time slices
●
     Multiple threads are the only possibility for a program to use
     multiple CPUs / cores (if they are available)
●
     Each Thread has a priority between MIN_PRIORITY and
     MAX_PRIORITY (currently from 1 to 10)
●
     Java implements fixed-priority preemptive scheduling
      –   at any given time, a Thread with the highest priority is running,
          but this is not guaranteed: lower-priority threads may be
          executed to avoid starvation
      –   if any higher-priority Thread appears, it is executed pausing others

    Java course – IAG0040                                          Lecture 10
    Anton Keks                                                         Slide 9
Synchronization
●
    Independent and asynchronous Threads are fine
    without synchronization
●
    However, access to shared data must be synchronized
     –   thread scheduling is unpredictable: threads may
         access (read-modify-write) variables in any order
●   Synchronization prevents interruption of critical regions
    in the code
●   Dijkstra's Dining Philosophers Problem is often used for
    illustration of various synchronization/concurrency
    problems

Java course – IAG0040                                 Lecture 10
Anton Keks                                              Slide 10
Synchronization (cont)
 ●
     Java provides the synchronized keyword
     –   it is used to obtain a lock on an arbitrary object
         instance
     –   you can declare synchronized blocks of code:
         synchronized (lockObject) { ... }
     –   code within the synchronized block is accessed
         atomically
     –   you can also declare methods as synchronized –
         the lock is obtained on the instance of the object
         or the Class object if method is static

Java course – IAG0040                                  Lecture 10
Anton Keks                                               Slide 11
Synchronization (cont)
 ●   Object class provides wait() and notify() methods
      –   both require acquiring a lock on the object first
          (synchronized)
      –   they can be used for signaling to different parts in the code
      –   wait() can have a timeout and may be interrupted
 ●   Java 1.5 provides many exciting new features for concurrent
     programming in the java.util.concurrent package
      –   Lock and ReadWriteLock implementations (e.g. ReentrantLock),
          Semaphore, etc provide additional features and sometimes better
          scalability
      –   ReentrantLock rlock = new ReentrantLock();
          rlock.lock();
          try { ... } finally { rlock.unlock(); }
Java course – IAG0040                                            Lecture 10
Anton Keks                                                         Slide 12
Thread safety
●    Rule #1: Document thread safety in Javadoc!!!
●    Many classes or methods can have various levels of thread safety
     –   Immutable – always thread-safe, because its state never changes
     –   Thread-safe – can be used in multiple threads concurrently (either
         synchronization is not needed or it is synchronized internally), this is a
         rather strict requirement
     –   Conditionally thread-safe – each individual operation may be thread safe,
         but certain sequences of operations may require external synchronization,
         e.g. Iterator returned by Vector and Hashtable
     –   Thread compatible – not thread safe, but thread safety can be achieved by
         external synchronization of method calls, e.g. StringBuilder, all Collections,
         etc
     –   Thread hostile – external synchronization of individual method calls will not
         make an object thread safe, this is rare and can be a result of bad design

    Java course – IAG0040                                                     Lecture 10
    Anton Keks                                                                  Slide 13
Timers and Tasks
 ●   Timer and TimerTask (both in java.util) can be used for conveniently
     scheduling task execution at intervals or with delays
 ●   Extend the abstract TimerTask to create your task (implement the
     run() method)
 ●
     Use a Timer for scheduling this task arbitrarily. Every instance of a
     Timer represents a single Thread.
      –   schedule() - schedules a task for either single or periodical
          execution. Counting to the next execution begins after the
          previous one is finished.
      –   scheduleAtFixedRate() - schedules with the exact period.
          Counting to the next execution is not affected by the previous
          one.
      –   any Timer can have many TimerTasks scheduled
Java course – IAG0040                                              Lecture 10
Anton Keks                                                           Slide 14
ThreadLocal
 ●
     java.lang.ThreadLocal can be used for storing
     independent data for each Thread (thread-local
     variables)
     –   All Threads share the same ThreadLocal instance, but
         every Thread only 'sees' data belonging to it
     –   Can be used for storing such things, as User ID,
         Transaction ID, etc which are handled by current
         Thread
 ●   ThreadLocal methods
     –   set(...) - sets the thread-local variable
     –   get() - retrieves the previously set thread-local variable
Java course – IAG0040                                        Lecture 10
Anton Keks                                                     Slide 15
More on java.util.concurrent
 ●
     Introduced in Java 1.5, besides higher-level synchronization classes it
     provides many useful functionality for reduced programming effort, more
     performance, reliability, maintainability, and productivity
 ●   Task scheduling framework: the Executor framework standardizes
     scheduling, invocation, execution, and control of asynchronous Runnable
     tasks (implementation includes thread pools)
 ●   Concurrent Collections: some new implementations of Map, List, and
     Queue
 ●   Atomic variables: atomic subpackage provides classes for atomically
     manipulating of variables, e.g. AtomicInteger (for higher performance)
 ●
     Synchronizers and Locks: more general purpose implementations with
     timeouts, reader/writer differentiation, non-nested scoping, etc
 ●   Nanosecond-granularity timing, e.g. System.nanotime();


Java course – IAG0040                                                 Lecture 10
Anton Keks                                                              Slide 16

More Related Content

What's hot

Thread Dump Analysis
Thread Dump AnalysisThread Dump Analysis
Thread Dump Analysis
Dmitry Buzdin
 
Process Synchronization And Deadlocks
Process Synchronization And DeadlocksProcess Synchronization And Deadlocks
Process Synchronization And Deadlocks
tech2click
 
Object and component based middleware for distributed system development
Object and component based middleware for distributed system developmentObject and component based middleware for distributed system development
Object and component based middleware for distributed system development
ektabhalwara
 

What's hot (20)

Unit II - 3 - Operating System - Process Synchronization
Unit II - 3 - Operating System - Process SynchronizationUnit II - 3 - Operating System - Process Synchronization
Unit II - 3 - Operating System - Process Synchronization
 
Golang 高性能实战
Golang 高性能实战Golang 高性能实战
Golang 高性能实战
 
The Java memory model made easy
The Java memory model made easyThe Java memory model made easy
The Java memory model made easy
 
Threads in Operating System | Multithreading | Interprocess Communication
Threads in Operating System | Multithreading | Interprocess CommunicationThreads in Operating System | Multithreading | Interprocess Communication
Threads in Operating System | Multithreading | Interprocess Communication
 
Java logging
Java loggingJava logging
Java logging
 
Thread Dump Analysis
Thread Dump AnalysisThread Dump Analysis
Thread Dump Analysis
 
Virtual memory
Virtual memoryVirtual memory
Virtual memory
 
Deadlock
DeadlockDeadlock
Deadlock
 
Unit II - 2 - Operating System - Threads
Unit II - 2 - Operating System - ThreadsUnit II - 2 - Operating System - Threads
Unit II - 2 - Operating System - Threads
 
Process Synchronization And Deadlocks
Process Synchronization And DeadlocksProcess Synchronization And Deadlocks
Process Synchronization And Deadlocks
 
Migrating to Java 11
Migrating to Java 11Migrating to Java 11
Migrating to Java 11
 
Ch1-Operating System Concepts
Ch1-Operating System ConceptsCh1-Operating System Concepts
Ch1-Operating System Concepts
 
Java Multithreading and Concurrency
Java Multithreading and ConcurrencyJava Multithreading and Concurrency
Java Multithreading and Concurrency
 
Java 9/10/11 - What's new and why you should upgrade
Java 9/10/11 - What's new and why you should upgradeJava 9/10/11 - What's new and why you should upgrade
Java 9/10/11 - What's new and why you should upgrade
 
Introduction to operating system, system calls and interrupts
Introduction to operating system, system calls and interruptsIntroduction to operating system, system calls and interrupts
Introduction to operating system, system calls and interrupts
 
Chapter 7 - Deadlocks
Chapter 7 - DeadlocksChapter 7 - Deadlocks
Chapter 7 - Deadlocks
 
Object and component based middleware for distributed system development
Object and component based middleware for distributed system developmentObject and component based middleware for distributed system development
Object and component based middleware for distributed system development
 
Android crash debugging
Android crash debuggingAndroid crash debugging
Android crash debugging
 
Dead Lock In Operating Systems
Dead Lock In Operating SystemsDead Lock In Operating Systems
Dead Lock In Operating Systems
 
SR-IOV: The Key Enabling Technology for Fully Virtualized HPC Clusters
SR-IOV: The Key Enabling Technology for Fully Virtualized HPC ClustersSR-IOV: The Key Enabling Technology for Fully Virtualized HPC Clusters
SR-IOV: The Key Enabling Technology for Fully Virtualized HPC Clusters
 

Viewers also liked

Multithreading In Java
Multithreading In JavaMultithreading In Java
Multithreading In Java
parag
 
Multithreading in java
Multithreading in javaMultithreading in java
Multithreading in java
Raghu nath
 
Java Thread Synchronization
Java Thread SynchronizationJava Thread Synchronization
Java Thread Synchronization
Benj Del Mundo
 
Java concurrency begining
Java concurrency   beginingJava concurrency   begining
Java concurrency begining
maksym220889
 
Java Colombo: Developing Highly Scalable Apps
Java Colombo: Developing Highly Scalable AppsJava Colombo: Developing Highly Scalable Apps
Java Colombo: Developing Highly Scalable Apps
Afkham Azeez
 

Viewers also liked (20)

Multithreading In Java
Multithreading In JavaMultithreading In Java
Multithreading In Java
 
Java multi threading
Java multi threadingJava multi threading
Java multi threading
 
Threads in JAVA
Threads in JAVAThreads in JAVA
Threads in JAVA
 
Multithreading in java
Multithreading in javaMultithreading in java
Multithreading in java
 
Java concurrency
Java concurrencyJava concurrency
Java concurrency
 
Java Multi Thead Programming
Java Multi Thead ProgrammingJava Multi Thead Programming
Java Multi Thead Programming
 
Java Concurrency in Practice
Java Concurrency in PracticeJava Concurrency in Practice
Java Concurrency in Practice
 
Java And Multithreading
Java And MultithreadingJava And Multithreading
Java And Multithreading
 
Java concurrency in practice
Java concurrency in practiceJava concurrency in practice
Java concurrency in practice
 
Design Patterns & JDK Examples
Design Patterns & JDK ExamplesDesign Patterns & JDK Examples
Design Patterns & JDK Examples
 
Threads concept in java
Threads concept in javaThreads concept in java
Threads concept in java
 
Multithread Programing in Java
Multithread Programing in JavaMultithread Programing in Java
Multithread Programing in Java
 
Java Thread Synchronization
Java Thread SynchronizationJava Thread Synchronization
Java Thread Synchronization
 
Java concurrency
Java concurrencyJava concurrency
Java concurrency
 
Java concurrency begining
Java concurrency   beginingJava concurrency   begining
Java concurrency begining
 
java Unit4 chapter1 applets
java Unit4 chapter1 appletsjava Unit4 chapter1 applets
java Unit4 chapter1 applets
 
THREADS EM JAVA: INTRODUÇÃO
THREADS EM JAVA: INTRODUÇÃOTHREADS EM JAVA: INTRODUÇÃO
THREADS EM JAVA: INTRODUÇÃO
 
Java Colombo: Developing Highly Scalable Apps
Java Colombo: Developing Highly Scalable AppsJava Colombo: Developing Highly Scalable Apps
Java Colombo: Developing Highly Scalable Apps
 
Java Concurrency Gotchas
Java Concurrency GotchasJava Concurrency Gotchas
Java Concurrency Gotchas
 
GPars: Groovy Parallelism for Java
GPars: Groovy Parallelism for JavaGPars: Groovy Parallelism for Java
GPars: Groovy Parallelism for Java
 

Similar to Java Course 10: Threads and Concurrency

Programming with Threads in Java
Programming with Threads in JavaProgramming with Threads in Java
Programming with Threads in Java
koji lin
 
Multithreading in Java Object Oriented Programming language
Multithreading in Java Object Oriented Programming languageMultithreading in Java Object Oriented Programming language
Multithreading in Java Object Oriented Programming language
arnavytstudio2814
 

Similar to Java Course 10: Threads and Concurrency (20)

Java Threads: Lightweight Processes
Java Threads: Lightweight ProcessesJava Threads: Lightweight Processes
Java Threads: Lightweight Processes
 
Programming with Threads in Java
Programming with Threads in JavaProgramming with Threads in Java
Programming with Threads in Java
 
1.17 Thread in java.pptx
1.17 Thread in java.pptx1.17 Thread in java.pptx
1.17 Thread in java.pptx
 
Threading in java - a pragmatic primer
Threading in java - a pragmatic primerThreading in java - a pragmatic primer
Threading in java - a pragmatic primer
 
Internet Programming with Java
Internet Programming with JavaInternet Programming with Java
Internet Programming with Java
 
Java
JavaJava
Java
 
Java unit 12
Java unit 12Java unit 12
Java unit 12
 
Multithreading programming in java
Multithreading programming in javaMultithreading programming in java
Multithreading programming in java
 
Java Course 9: Networking and Reflection
Java Course 9: Networking and ReflectionJava Course 9: Networking and Reflection
Java Course 9: Networking and Reflection
 
Multithreading in java
Multithreading in javaMultithreading in java
Multithreading in java
 
Multithreading in java
Multithreading in javaMultithreading in java
Multithreading in java
 
Wait for your fortune without Blocking!
Wait for your fortune without Blocking!Wait for your fortune without Blocking!
Wait for your fortune without Blocking!
 
Multithreading in Java Object Oriented Programming language
Multithreading in Java Object Oriented Programming languageMultithreading in Java Object Oriented Programming language
Multithreading in Java Object Oriented Programming language
 
Java Thread
Java ThreadJava Thread
Java Thread
 
Basics of Java Concurrency
Basics of Java ConcurrencyBasics of Java Concurrency
Basics of Java Concurrency
 
Java Course 3: OOP
Java Course 3: OOPJava Course 3: OOP
Java Course 3: OOP
 
Java Course 4: Exceptions & Collections
Java Course 4: Exceptions & CollectionsJava Course 4: Exceptions & Collections
Java Course 4: Exceptions & Collections
 
Chap2 2 1
Chap2 2 1Chap2 2 1
Chap2 2 1
 
Threads in Java
Threads in JavaThreads in Java
Threads in Java
 
Java Threads And Concurrency Presentation. 2024
Java Threads And Concurrency Presentation. 2024Java Threads And Concurrency Presentation. 2024
Java Threads And Concurrency Presentation. 2024
 

More from Anton Keks

More from Anton Keks (17)

Being a professional software tester
Being a professional software testerBeing a professional software tester
Being a professional software tester
 
Java Course 14: Beans, Applets, GUI
Java Course 14: Beans, Applets, GUIJava Course 14: Beans, Applets, GUI
Java Course 14: Beans, Applets, GUI
 
Java Course 13: JDBC & Logging
Java Course 13: JDBC & LoggingJava Course 13: JDBC & Logging
Java Course 13: JDBC & Logging
 
Java Course 12: XML & XSL, Web & Servlets
Java Course 12: XML & XSL, Web & ServletsJava Course 12: XML & XSL, Web & Servlets
Java Course 12: XML & XSL, Web & Servlets
 
Java Course 11: Design Patterns
Java Course 11: Design PatternsJava Course 11: Design Patterns
Java Course 11: Design Patterns
 
Java Course 8: I/O, Files and Streams
Java Course 8: I/O, Files and StreamsJava Course 8: I/O, Files and Streams
Java Course 8: I/O, Files and Streams
 
Java Course 7: Text processing, Charsets & Encodings
Java Course 7: Text processing, Charsets & EncodingsJava Course 7: Text processing, Charsets & Encodings
Java Course 7: Text processing, Charsets & Encodings
 
Java Course 6: Introduction to Agile
Java Course 6: Introduction to AgileJava Course 6: Introduction to Agile
Java Course 6: Introduction to Agile
 
Java Course 5: Enums, Generics, Assertions
Java Course 5: Enums, Generics, AssertionsJava Course 5: Enums, Generics, Assertions
Java Course 5: Enums, Generics, Assertions
 
Java Course 2: Basics
Java Course 2: BasicsJava Course 2: Basics
Java Course 2: Basics
 
Java Course 1: Introduction
Java Course 1: IntroductionJava Course 1: Introduction
Java Course 1: Introduction
 
Java Course 15: Ant, Scripting, Spring, Hibernate
Java Course 15: Ant, Scripting, Spring, HibernateJava Course 15: Ant, Scripting, Spring, Hibernate
Java Course 15: Ant, Scripting, Spring, Hibernate
 
Choose a pattern for a problem
Choose a pattern for a problemChoose a pattern for a problem
Choose a pattern for a problem
 
Simple Pure Java
Simple Pure JavaSimple Pure Java
Simple Pure Java
 
Database Refactoring
Database RefactoringDatabase Refactoring
Database Refactoring
 
Scrum is not enough - being a successful agile engineer
Scrum is not enough - being a successful agile engineerScrum is not enough - being a successful agile engineer
Scrum is not enough - being a successful agile engineer
 
Being a Professional Software Developer
Being a Professional Software DeveloperBeing a Professional Software Developer
Being a Professional Software Developer
 

Recently uploaded

Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Safe Software
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Safe Software
 

Recently uploaded (20)

"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 ...
 
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
 
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...
 
Understanding the FAA Part 107 License ..
Understanding the FAA Part 107 License ..Understanding the FAA Part 107 License ..
Understanding the FAA Part 107 License ..
 
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
 
Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...
 
Vector Search -An Introduction in Oracle Database 23ai.pptx
Vector Search -An Introduction in Oracle Database 23ai.pptxVector Search -An Introduction in Oracle Database 23ai.pptx
Vector Search -An Introduction in Oracle Database 23ai.pptx
 
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
 
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot TakeoffStrategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
 
[BuildWithAI] Introduction to Gemini.pdf
[BuildWithAI] Introduction to Gemini.pdf[BuildWithAI] Introduction to Gemini.pdf
[BuildWithAI] Introduction to Gemini.pdf
 
Six Myths about Ontologies: The Basics of Formal Ontology
Six Myths about Ontologies: The Basics of Formal OntologySix Myths about Ontologies: The Basics of Formal Ontology
Six Myths about Ontologies: The Basics of Formal Ontology
 
WSO2's API Vision: Unifying Control, Empowering Developers
WSO2's API Vision: Unifying Control, Empowering DevelopersWSO2's API Vision: Unifying Control, Empowering Developers
WSO2's API Vision: Unifying Control, Empowering Developers
 
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
 
Artificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : UncertaintyArtificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : Uncertainty
 
AI+A11Y 11MAY2024 HYDERBAD GAAD 2024 - HelloA11Y (11 May 2024)
AI+A11Y 11MAY2024 HYDERBAD GAAD 2024 - HelloA11Y (11 May 2024)AI+A11Y 11MAY2024 HYDERBAD GAAD 2024 - HelloA11Y (11 May 2024)
AI+A11Y 11MAY2024 HYDERBAD GAAD 2024 - HelloA11Y (11 May 2024)
 
AI in Action: Real World Use Cases by Anitaraj
AI in Action: Real World Use Cases by AnitarajAI in Action: Real World Use Cases by Anitaraj
AI in Action: Real World Use Cases by Anitaraj
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
 
Exploring Multimodal Embeddings with Milvus
Exploring Multimodal Embeddings with MilvusExploring Multimodal Embeddings with Milvus
Exploring Multimodal Embeddings with Milvus
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
 
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
 

Java Course 10: Threads and Concurrency

  • 1. Java course - IAG0040 Threads & Concurrency Anton Keks 2011
  • 2. Introduction to Threads ● A Thread is a lightweight process ● A Thread is a single sequential flow of control within a program A Program A Program Java course – IAG0040 Lecture 10 Anton Keks Slide 2
  • 3. More formal definition ● A thread is pure activity, i.e. the information about the current position of execution (instruction pointer), the registers and the current stack ● An address space is a range of addressable memory that is only accessible by activities that are allowed to read/write from it ● A process consists of an address space and one or multiple threads Java course – IAG0040 Lecture 10 Anton Keks Slide 3
  • 4. Threads & Java ● Java supports Threads and synchronization natively ● Threads can be used for doing two or more tasks at once ● main() method is always executed in the “main” thread – there are always several more system threads running in your Java program, e.g. garbage collector ● You can always start as many new threads as your program needs using the Thread class Java course – IAG0040 Lecture 10 Anton Keks Slide 4
  • 5. Thread class ● Threads run Runnable tasks, there are two possible implementations – extend the Thread class itself, overriding the run method: class MegaThread extends Thread { ... } Thread t = new MegaThread(); – implement the Runnable interface and pass it to a new Thread: class MegaRunnable implements Runnable { ... } Thread t = new Thread(new MegaRunnable()); ● Every Thread has a name: it can be specified on creation or using the setName() method ● Thread class provides some useful static methods: – currentThread() returns the current Thread's instance – sleep() pauses the current Thread for the given time – yield() allows other Threads to run by pausing the current one Java course – IAG0040 Lecture 10 Anton Keks Slide 5
  • 6. Thread class (cont) ● start() starts the new Thread in the background, note: run() method doesn't start the Thread! ● join() waits for another Thread to die ● setDaemon(true) sets the daemon flag. JVM terminates if there are only daemon threads left running. ● getId() returns a unique Id (long) of the Thread ● isAlive() tests if the Thread is alive (started and not dead) ● getState() provides more information on the state ● There are many other interesting is/get methods, see Javadoc Java course – IAG0040 Lecture 10 Anton Keks Slide 6
  • 7. Exception handling ● Each thread has a default top-level exception handler – that calls printStackTrace() ● Just like the main thread, where the main() method is executed ● If an exception is thrown out of a thread, the thread is terminated Java course – IAG0040 Lecture 10 Anton Keks Slide 7
  • 8. Interrupting Threads ● There are many deprecated methods in the Thread class, which have been proved to be dangerous (may cause deadlocks, etc): suspend(), resume(), stop(), destroy(), etc ● Instead, interrupt() can be used – it interrupts blocking/waiting method calls, e.g. sleep(), wait(), join(), etc, with an InterruptedException – it signals the Thread that it should terminate ● interrupted flag can be checked using either the static Thread.interrupted() or isInterrupted() method – it is a safe and graceful way to interrupt a Thread, because it involves interaction from the Thread itself Java course – IAG0040 Lecture 10 Anton Keks Slide 8
  • 9. Scheduling ● Scheduling is execution of multiple threads on a single CPU, dividing available CPU time into time slices ● Multiple threads are the only possibility for a program to use multiple CPUs / cores (if they are available) ● Each Thread has a priority between MIN_PRIORITY and MAX_PRIORITY (currently from 1 to 10) ● Java implements fixed-priority preemptive scheduling – at any given time, a Thread with the highest priority is running, but this is not guaranteed: lower-priority threads may be executed to avoid starvation – if any higher-priority Thread appears, it is executed pausing others Java course – IAG0040 Lecture 10 Anton Keks Slide 9
  • 10. Synchronization ● Independent and asynchronous Threads are fine without synchronization ● However, access to shared data must be synchronized – thread scheduling is unpredictable: threads may access (read-modify-write) variables in any order ● Synchronization prevents interruption of critical regions in the code ● Dijkstra's Dining Philosophers Problem is often used for illustration of various synchronization/concurrency problems Java course – IAG0040 Lecture 10 Anton Keks Slide 10
  • 11. Synchronization (cont) ● Java provides the synchronized keyword – it is used to obtain a lock on an arbitrary object instance – you can declare synchronized blocks of code: synchronized (lockObject) { ... } – code within the synchronized block is accessed atomically – you can also declare methods as synchronized – the lock is obtained on the instance of the object or the Class object if method is static Java course – IAG0040 Lecture 10 Anton Keks Slide 11
  • 12. Synchronization (cont) ● Object class provides wait() and notify() methods – both require acquiring a lock on the object first (synchronized) – they can be used for signaling to different parts in the code – wait() can have a timeout and may be interrupted ● Java 1.5 provides many exciting new features for concurrent programming in the java.util.concurrent package – Lock and ReadWriteLock implementations (e.g. ReentrantLock), Semaphore, etc provide additional features and sometimes better scalability – ReentrantLock rlock = new ReentrantLock(); rlock.lock(); try { ... } finally { rlock.unlock(); } Java course – IAG0040 Lecture 10 Anton Keks Slide 12
  • 13. Thread safety ● Rule #1: Document thread safety in Javadoc!!! ● Many classes or methods can have various levels of thread safety – Immutable – always thread-safe, because its state never changes – Thread-safe – can be used in multiple threads concurrently (either synchronization is not needed or it is synchronized internally), this is a rather strict requirement – Conditionally thread-safe – each individual operation may be thread safe, but certain sequences of operations may require external synchronization, e.g. Iterator returned by Vector and Hashtable – Thread compatible – not thread safe, but thread safety can be achieved by external synchronization of method calls, e.g. StringBuilder, all Collections, etc – Thread hostile – external synchronization of individual method calls will not make an object thread safe, this is rare and can be a result of bad design Java course – IAG0040 Lecture 10 Anton Keks Slide 13
  • 14. Timers and Tasks ● Timer and TimerTask (both in java.util) can be used for conveniently scheduling task execution at intervals or with delays ● Extend the abstract TimerTask to create your task (implement the run() method) ● Use a Timer for scheduling this task arbitrarily. Every instance of a Timer represents a single Thread. – schedule() - schedules a task for either single or periodical execution. Counting to the next execution begins after the previous one is finished. – scheduleAtFixedRate() - schedules with the exact period. Counting to the next execution is not affected by the previous one. – any Timer can have many TimerTasks scheduled Java course – IAG0040 Lecture 10 Anton Keks Slide 14
  • 15. ThreadLocal ● java.lang.ThreadLocal can be used for storing independent data for each Thread (thread-local variables) – All Threads share the same ThreadLocal instance, but every Thread only 'sees' data belonging to it – Can be used for storing such things, as User ID, Transaction ID, etc which are handled by current Thread ● ThreadLocal methods – set(...) - sets the thread-local variable – get() - retrieves the previously set thread-local variable Java course – IAG0040 Lecture 10 Anton Keks Slide 15
  • 16. More on java.util.concurrent ● Introduced in Java 1.5, besides higher-level synchronization classes it provides many useful functionality for reduced programming effort, more performance, reliability, maintainability, and productivity ● Task scheduling framework: the Executor framework standardizes scheduling, invocation, execution, and control of asynchronous Runnable tasks (implementation includes thread pools) ● Concurrent Collections: some new implementations of Map, List, and Queue ● Atomic variables: atomic subpackage provides classes for atomically manipulating of variables, e.g. AtomicInteger (for higher performance) ● Synchronizers and Locks: more general purpose implementations with timeouts, reader/writer differentiation, non-nested scoping, etc ● Nanosecond-granularity timing, e.g. System.nanotime(); Java course – IAG0040 Lecture 10 Anton Keks Slide 16