SlideShare ist ein Scribd-Unternehmen logo
1 von 16
Downloaden Sie, um offline zu lesen
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

Weitere ähnliche Inhalte

Was ist angesagt?

Infrastructure at Scale: Apache Kafka, Twitter Storm & Elastic Search (ARC303...
Infrastructure at Scale: Apache Kafka, Twitter Storm & Elastic Search (ARC303...Infrastructure at Scale: Apache Kafka, Twitter Storm & Elastic Search (ARC303...
Infrastructure at Scale: Apache Kafka, Twitter Storm & Elastic Search (ARC303...Amazon Web Services
 
DBA Tasks in Oracle Autonomous Database
DBA Tasks in Oracle Autonomous DatabaseDBA Tasks in Oracle Autonomous Database
DBA Tasks in Oracle Autonomous DatabaseSinanPetrusToma
 
Introduction to memcached
Introduction to memcachedIntroduction to memcached
Introduction to memcachedJurriaan Persyn
 
Oracle Client Failover - Under The Hood
Oracle Client Failover - Under The HoodOracle Client Failover - Under The Hood
Oracle Client Failover - Under The HoodLudovico Caldara
 
Introduction to Storm
Introduction to Storm Introduction to Storm
Introduction to Storm Chandler Huang
 
Introduction to Apache Flink - Fast and reliable big data processing
Introduction to Apache Flink - Fast and reliable big data processingIntroduction to Apache Flink - Fast and reliable big data processing
Introduction to Apache Flink - Fast and reliable big data processingTill Rohrmann
 
Dynamo and BigTable in light of the CAP theorem
Dynamo and BigTable in light of the CAP theoremDynamo and BigTable in light of the CAP theorem
Dynamo and BigTable in light of the CAP theoremGrisha Weintraub
 
Tech Talk: RocksDB Slides by Dhruba Borthakur & Haobo Xu of Facebook
Tech Talk: RocksDB Slides by Dhruba Borthakur & Haobo Xu of FacebookTech Talk: RocksDB Slides by Dhruba Borthakur & Haobo Xu of Facebook
Tech Talk: RocksDB Slides by Dhruba Borthakur & Haobo Xu of FacebookThe Hive
 
Filesystem Comparison: NFS vs GFS2 vs OCFS2
Filesystem Comparison: NFS vs GFS2 vs OCFS2Filesystem Comparison: NFS vs GFS2 vs OCFS2
Filesystem Comparison: NFS vs GFS2 vs OCFS2Giuseppe Paterno'
 
Introduction to Kafka and Zookeeper
Introduction to Kafka and ZookeeperIntroduction to Kafka and Zookeeper
Introduction to Kafka and ZookeeperRahul Jain
 
Accelerating TensorFlow with RDMA for high-performance deep learning
Accelerating TensorFlow with RDMA for high-performance deep learningAccelerating TensorFlow with RDMA for high-performance deep learning
Accelerating TensorFlow with RDMA for high-performance deep learningDataWorks Summit
 
ceph optimization on ssd ilsoo byun-short
ceph optimization on ssd ilsoo byun-shortceph optimization on ssd ilsoo byun-short
ceph optimization on ssd ilsoo byun-shortNAVER D2
 
Oracle RAC 19c - the Basis for the Autonomous Database
Oracle RAC 19c - the Basis for the Autonomous DatabaseOracle RAC 19c - the Basis for the Autonomous Database
Oracle RAC 19c - the Basis for the Autonomous DatabaseMarkus Michalewicz
 
ORC File - Optimizing Your Big Data
ORC File - Optimizing Your Big DataORC File - Optimizing Your Big Data
ORC File - Optimizing Your Big DataDataWorks Summit
 
Linux kernel debugging
Linux kernel debuggingLinux kernel debugging
Linux kernel debugginglibfetion
 

Was ist angesagt? (20)

Infrastructure at Scale: Apache Kafka, Twitter Storm & Elastic Search (ARC303...
Infrastructure at Scale: Apache Kafka, Twitter Storm & Elastic Search (ARC303...Infrastructure at Scale: Apache Kafka, Twitter Storm & Elastic Search (ARC303...
Infrastructure at Scale: Apache Kafka, Twitter Storm & Elastic Search (ARC303...
 
DBA Tasks in Oracle Autonomous Database
DBA Tasks in Oracle Autonomous DatabaseDBA Tasks in Oracle Autonomous Database
DBA Tasks in Oracle Autonomous Database
 
Introduction to memcached
Introduction to memcachedIntroduction to memcached
Introduction to memcached
 
Oracle Client Failover - Under The Hood
Oracle Client Failover - Under The HoodOracle Client Failover - Under The Hood
Oracle Client Failover - Under The Hood
 
Oracle Data Guard
Oracle Data GuardOracle Data Guard
Oracle Data Guard
 
Introduction to Storm
Introduction to Storm Introduction to Storm
Introduction to Storm
 
Introduction to Apache Flink - Fast and reliable big data processing
Introduction to Apache Flink - Fast and reliable big data processingIntroduction to Apache Flink - Fast and reliable big data processing
Introduction to Apache Flink - Fast and reliable big data processing
 
Dynamo and BigTable in light of the CAP theorem
Dynamo and BigTable in light of the CAP theoremDynamo and BigTable in light of the CAP theorem
Dynamo and BigTable in light of the CAP theorem
 
Tech Talk: RocksDB Slides by Dhruba Borthakur & Haobo Xu of Facebook
Tech Talk: RocksDB Slides by Dhruba Borthakur & Haobo Xu of FacebookTech Talk: RocksDB Slides by Dhruba Borthakur & Haobo Xu of Facebook
Tech Talk: RocksDB Slides by Dhruba Borthakur & Haobo Xu of Facebook
 
Kafka 101
Kafka 101Kafka 101
Kafka 101
 
Filesystem Comparison: NFS vs GFS2 vs OCFS2
Filesystem Comparison: NFS vs GFS2 vs OCFS2Filesystem Comparison: NFS vs GFS2 vs OCFS2
Filesystem Comparison: NFS vs GFS2 vs OCFS2
 
Introduction to Kafka and Zookeeper
Introduction to Kafka and ZookeeperIntroduction to Kafka and Zookeeper
Introduction to Kafka and Zookeeper
 
Accelerating TensorFlow with RDMA for high-performance deep learning
Accelerating TensorFlow with RDMA for high-performance deep learningAccelerating TensorFlow with RDMA for high-performance deep learning
Accelerating TensorFlow with RDMA for high-performance deep learning
 
Linux IO
Linux IOLinux IO
Linux IO
 
Apache Spark Architecture
Apache Spark ArchitectureApache Spark Architecture
Apache Spark Architecture
 
Introduction to Apache Beam
Introduction to Apache BeamIntroduction to Apache Beam
Introduction to Apache Beam
 
ceph optimization on ssd ilsoo byun-short
ceph optimization on ssd ilsoo byun-shortceph optimization on ssd ilsoo byun-short
ceph optimization on ssd ilsoo byun-short
 
Oracle RAC 19c - the Basis for the Autonomous Database
Oracle RAC 19c - the Basis for the Autonomous DatabaseOracle RAC 19c - the Basis for the Autonomous Database
Oracle RAC 19c - the Basis for the Autonomous Database
 
ORC File - Optimizing Your Big Data
ORC File - Optimizing Your Big DataORC File - Optimizing Your Big Data
ORC File - Optimizing Your Big Data
 
Linux kernel debugging
Linux kernel debuggingLinux kernel debugging
Linux kernel debugging
 

Andere mochten auch

Multithreading In Java
Multithreading In JavaMultithreading In Java
Multithreading In Javaparag
 
Java multi threading
Java multi threadingJava multi threading
Java multi threadingRaja Sekhar
 
Multithreading in java
Multithreading in javaMultithreading in java
Multithreading in javaRaghu nath
 
Java concurrency
Java concurrencyJava concurrency
Java concurrencyducquoc_vn
 
Java Multi Thead Programming
Java Multi Thead ProgrammingJava Multi Thead Programming
Java Multi Thead ProgrammingNishant Mevawala
 
Java Concurrency in Practice
Java Concurrency in PracticeJava Concurrency in Practice
Java Concurrency in PracticeAlina Dolgikh
 
Java And Multithreading
Java And MultithreadingJava And Multithreading
Java And MultithreadingShraddha
 
Java concurrency in practice
Java concurrency in practiceJava concurrency in practice
Java concurrency in practiceMikalai Alimenkou
 
Design Patterns & JDK Examples
Design Patterns & JDK ExamplesDesign Patterns & JDK Examples
Design Patterns & JDK ExamplesEnder Aydin Orak
 
Multithread Programing in Java
Multithread Programing in JavaMultithread Programing in Java
Multithread Programing in JavaM. Raihan
 
Java Multithreading and Concurrency
Java Multithreading and ConcurrencyJava Multithreading and Concurrency
Java Multithreading and ConcurrencyRajesh Ananda Kumar
 
Java Thread Synchronization
Java Thread SynchronizationJava Thread Synchronization
Java Thread SynchronizationBenj Del Mundo
 
Java concurrency begining
Java concurrency   beginingJava concurrency   begining
Java concurrency beginingmaksym220889
 
java Unit4 chapter1 applets
java Unit4 chapter1 appletsjava Unit4 chapter1 applets
java Unit4 chapter1 appletsraksharao
 
Java Colombo: Developing Highly Scalable Apps
Java Colombo: Developing Highly Scalable AppsJava Colombo: Developing Highly Scalable Apps
Java Colombo: Developing Highly Scalable AppsAfkham Azeez
 
Java Concurrency Gotchas
Java Concurrency GotchasJava Concurrency Gotchas
Java Concurrency GotchasAlex Miller
 

Andere mochten auch (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
 

Ähnlich wie Java Course 10: Threads and Concurrency

Java Threads: Lightweight Processes
Java Threads: Lightweight ProcessesJava Threads: Lightweight Processes
Java Threads: Lightweight ProcessesIsuru Perera
 
Programming with Threads in Java
Programming with Threads in JavaProgramming with Threads in Java
Programming with Threads in Javakoji lin
 
1.17 Thread in java.pptx
1.17 Thread in java.pptx1.17 Thread in java.pptx
1.17 Thread in java.pptxTREXSHyNE
 
Multithreading programming in java
Multithreading programming in javaMultithreading programming in java
Multithreading programming in javaElizabeth alexander
 
Java Course 9: Networking and Reflection
Java Course 9: Networking and ReflectionJava Course 9: Networking and Reflection
Java Course 9: Networking and ReflectionAnton Keks
 
Multithreading in java
Multithreading in javaMultithreading in java
Multithreading in javaKavitha713564
 
Multithreading in java
Multithreading in javaMultithreading in java
Multithreading in javaKavitha713564
 
Wait for your fortune without Blocking!
Wait for your fortune without Blocking!Wait for your fortune without Blocking!
Wait for your fortune without Blocking!Roman Elizarov
 
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 languagearnavytstudio2814
 
Basics of Java Concurrency
Basics of Java ConcurrencyBasics of Java Concurrency
Basics of Java Concurrencykshanth2101
 
Java Course 3: OOP
Java Course 3: OOPJava Course 3: OOP
Java Course 3: OOPAnton Keks
 
Java Course 4: Exceptions & Collections
Java Course 4: Exceptions & CollectionsJava Course 4: Exceptions & Collections
Java Course 4: Exceptions & CollectionsAnton Keks
 
Java Threads And Concurrency Presentation. 2024
Java Threads And Concurrency Presentation. 2024Java Threads And Concurrency Presentation. 2024
Java Threads And Concurrency Presentation. 2024kashyapneha2809
 

Ähnlich wie 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
 

Mehr von Anton Keks

Being a professional software tester
Being a professional software testerBeing a professional software tester
Being a professional software testerAnton Keks
 
Java Course 14: Beans, Applets, GUI
Java Course 14: Beans, Applets, GUIJava Course 14: Beans, Applets, GUI
Java Course 14: Beans, Applets, GUIAnton Keks
 
Java Course 13: JDBC & Logging
Java Course 13: JDBC & LoggingJava Course 13: JDBC & Logging
Java Course 13: JDBC & LoggingAnton Keks
 
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 & ServletsAnton Keks
 
Java Course 11: Design Patterns
Java Course 11: Design PatternsJava Course 11: Design Patterns
Java Course 11: Design PatternsAnton Keks
 
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 StreamsAnton Keks
 
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 & EncodingsAnton Keks
 
Java Course 6: Introduction to Agile
Java Course 6: Introduction to AgileJava Course 6: Introduction to Agile
Java Course 6: Introduction to AgileAnton Keks
 
Java Course 5: Enums, Generics, Assertions
Java Course 5: Enums, Generics, AssertionsJava Course 5: Enums, Generics, Assertions
Java Course 5: Enums, Generics, AssertionsAnton Keks
 
Java Course 2: Basics
Java Course 2: BasicsJava Course 2: Basics
Java Course 2: BasicsAnton Keks
 
Java Course 1: Introduction
Java Course 1: IntroductionJava Course 1: Introduction
Java Course 1: IntroductionAnton Keks
 
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, HibernateAnton Keks
 
Choose a pattern for a problem
Choose a pattern for a problemChoose a pattern for a problem
Choose a pattern for a problemAnton Keks
 
Simple Pure Java
Simple Pure JavaSimple Pure Java
Simple Pure JavaAnton Keks
 
Database Refactoring
Database RefactoringDatabase Refactoring
Database RefactoringAnton Keks
 
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 engineerAnton Keks
 
Being a Professional Software Developer
Being a Professional Software DeveloperBeing a Professional Software Developer
Being a Professional Software DeveloperAnton Keks
 

Mehr von 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
 

Kürzlich hochgeladen

DBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor PresentationDBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor PresentationDropbox
 
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...apidays
 
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...DianaGray10
 
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 TerraformAndrey Devyatkin
 
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 FresherRemote DBA Services
 
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...apidays
 
FWD Group - Insurer Innovation Award 2024
FWD Group - Insurer Innovation Award 2024FWD Group - Insurer Innovation Award 2024
FWD Group - Insurer Innovation Award 2024The Digital Insurer
 
CNIC Information System with Pakdata Cf In Pakistan
CNIC Information System with Pakdata Cf In PakistanCNIC Information System with Pakdata Cf In Pakistan
CNIC Information System with Pakdata Cf In Pakistandanishmna97
 
Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...
Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...
Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...Zilliz
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerThousandEyes
 
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 businesspanagenda
 
2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...Martijn de Jong
 
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 FMESafe Software
 
DEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
DEV meet-up UiPath Document Understanding May 7 2024 AmsterdamDEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
DEV meet-up UiPath Document Understanding May 7 2024 AmsterdamUiPathCommunity
 
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost SavingRepurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost SavingEdi Saputra
 
[BuildWithAI] Introduction to Gemini.pdf
[BuildWithAI] Introduction to Gemini.pdf[BuildWithAI] Introduction to Gemini.pdf
[BuildWithAI] Introduction to Gemini.pdfSandro Moreira
 
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024Victor Rentea
 
"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 ...Zilliz
 
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data DiscoveryTrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data DiscoveryTrustArc
 
MS Copilot expands with MS Graph connectors
MS Copilot expands with MS Graph connectorsMS Copilot expands with MS Graph connectors
MS Copilot expands with MS Graph connectorsNanddeep Nachan
 

Kürzlich hochgeladen (20)

DBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor PresentationDBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor Presentation
 
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
 
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
 
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
 
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
 
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
 
FWD Group - Insurer Innovation Award 2024
FWD Group - Insurer Innovation Award 2024FWD Group - Insurer Innovation Award 2024
FWD Group - Insurer Innovation Award 2024
 
CNIC Information System with Pakdata Cf In Pakistan
CNIC Information System with Pakdata Cf In PakistanCNIC Information System with Pakdata Cf In Pakistan
CNIC Information System with Pakdata Cf In Pakistan
 
Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...
Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...
Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected Worker
 
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
 
2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...
 
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
 
DEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
DEV meet-up UiPath Document Understanding May 7 2024 AmsterdamDEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
DEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
 
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost SavingRepurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
 
[BuildWithAI] Introduction to Gemini.pdf
[BuildWithAI] Introduction to Gemini.pdf[BuildWithAI] Introduction to Gemini.pdf
[BuildWithAI] Introduction to Gemini.pdf
 
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
 
"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 ...
 
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data DiscoveryTrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
 
MS Copilot expands with MS Graph connectors
MS Copilot expands with MS Graph connectorsMS Copilot expands with MS Graph connectors
MS Copilot expands with MS Graph connectors
 

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