SlideShare une entreprise Scribd logo
1  sur  16
Télécharger pour lire hors ligne
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

Contenu connexe

Tendances

Oracle GoldenGate Roadmap Oracle OpenWorld 2020
Oracle GoldenGate Roadmap Oracle OpenWorld 2020 Oracle GoldenGate Roadmap Oracle OpenWorld 2020
Oracle GoldenGate Roadmap Oracle OpenWorld 2020
Oracle
 

Tendances (20)

Oracle GoldenGate Roadmap Oracle OpenWorld 2020
Oracle GoldenGate Roadmap Oracle OpenWorld 2020 Oracle GoldenGate Roadmap Oracle OpenWorld 2020
Oracle GoldenGate Roadmap Oracle OpenWorld 2020
 
CockroachDB
CockroachDBCockroachDB
CockroachDB
 
Inside the jvm
Inside the jvmInside the jvm
Inside the jvm
 
Extreme Replication - Performance Tuning Oracle GoldenGate
Extreme Replication - Performance Tuning Oracle GoldenGateExtreme Replication - Performance Tuning Oracle GoldenGate
Extreme Replication - Performance Tuning Oracle GoldenGate
 
Your tuning arsenal: AWR, ADDM, ASH, Metrics and Advisors
Your tuning arsenal: AWR, ADDM, ASH, Metrics and AdvisorsYour tuning arsenal: AWR, ADDM, ASH, Metrics and Advisors
Your tuning arsenal: AWR, ADDM, ASH, Metrics and Advisors
 
Backup and recovery in oracle
Backup and recovery in oracleBackup and recovery in oracle
Backup and recovery in oracle
 
Anatomy of a Container: Namespaces, cgroups & Some Filesystem Magic - LinuxCon
Anatomy of a Container: Namespaces, cgroups & Some Filesystem Magic - LinuxConAnatomy of a Container: Namespaces, cgroups & Some Filesystem Magic - LinuxCon
Anatomy of a Container: Namespaces, cgroups & Some Filesystem Magic - LinuxCon
 
Inside HDFS Append
Inside HDFS AppendInside HDFS Append
Inside HDFS Append
 
Oracle Database in-Memory Overivew
Oracle Database in-Memory OverivewOracle Database in-Memory Overivew
Oracle Database in-Memory Overivew
 
스프링 어플리케이션의 문제해결사례와 안티패턴
스프링 어플리케이션의 문제해결사례와 안티패턴스프링 어플리케이션의 문제해결사례와 안티패턴
스프링 어플리케이션의 문제해결사례와 안티패턴
 
Building a data warehouse with Pentaho and Docker
Building a data warehouse with Pentaho and DockerBuilding a data warehouse with Pentaho and Docker
Building a data warehouse with Pentaho and Docker
 
Oracle ASM Training
Oracle ASM TrainingOracle ASM Training
Oracle ASM Training
 
[오픈소스컨설팅]RHEL7/CentOS7 Pacemaker기반-HA시스템구성-v1.0
[오픈소스컨설팅]RHEL7/CentOS7 Pacemaker기반-HA시스템구성-v1.0[오픈소스컨설팅]RHEL7/CentOS7 Pacemaker기반-HA시스템구성-v1.0
[오픈소스컨설팅]RHEL7/CentOS7 Pacemaker기반-HA시스템구성-v1.0
 
Automate Oracle database patches and upgrades using Fleet Provisioning and Pa...
Automate Oracle database patches and upgrades using Fleet Provisioning and Pa...Automate Oracle database patches and upgrades using Fleet Provisioning and Pa...
Automate Oracle database patches and upgrades using Fleet Provisioning and Pa...
 
Migration to Oracle Multitenant
Migration to Oracle MultitenantMigration to Oracle Multitenant
Migration to Oracle Multitenant
 
Running MariaDB in multiple data centers
Running MariaDB in multiple data centersRunning MariaDB in multiple data centers
Running MariaDB in multiple data centers
 
PostgreSQL HA
PostgreSQL   HAPostgreSQL   HA
PostgreSQL HA
 
Oracle_Multitenant_19c_-_All_About_Pluggable_D.pdf
Oracle_Multitenant_19c_-_All_About_Pluggable_D.pdfOracle_Multitenant_19c_-_All_About_Pluggable_D.pdf
Oracle_Multitenant_19c_-_All_About_Pluggable_D.pdf
 
4.3 MySQL + PHP
4.3 MySQL + PHP4.3 MySQL + PHP
4.3 MySQL + PHP
 
Yapp methodology anjo-kolk
Yapp methodology anjo-kolkYapp methodology anjo-kolk
Yapp methodology anjo-kolk
 

En vedette

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
 

En vedette (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 Multithreading and Concurrency
Java Multithreading and ConcurrencyJava Multithreading and Concurrency
Java Multithreading and Concurrency
 
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
 

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

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

Plus de Anton Keks

Plus de 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
 

Dernier

Why Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businessWhy Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire business
panagenda
 

Dernier (20)

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
 
GenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdfGenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdf
 
Why Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businessWhy Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire business
 
🐬 The future of MySQL is Postgres 🐘
🐬  The future of MySQL is Postgres   🐘🐬  The future of MySQL is Postgres   🐘
🐬 The future of MySQL is Postgres 🐘
 
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
 
Automating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps ScriptAutomating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps Script
 
Scaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationScaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organization
 
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, AdobeApidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
 
Data Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonData Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt Robison
 
Exploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone ProcessorsExploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone Processors
 
Manulife - Insurer Innovation Award 2024
Manulife - Insurer Innovation Award 2024Manulife - Insurer Innovation Award 2024
Manulife - Insurer Innovation Award 2024
 
Boost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityBoost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivity
 
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin WoodPolkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
 
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
 
HTML Injection Attacks: Impact and Mitigation Strategies
HTML Injection Attacks: Impact and Mitigation StrategiesHTML Injection Attacks: Impact and Mitigation Strategies
HTML Injection Attacks: Impact and Mitigation Strategies
 
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
 
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
 
A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?
 
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdfUnderstanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
 
Artificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : UncertaintyArtificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : Uncertainty
 

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