SlideShare a Scribd company logo
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

6 cpu scheduling
6 cpu scheduling6 cpu scheduling
6 cpu scheduling
BaliThorat1
 
OS Process and Thread Concepts
OS Process and Thread ConceptsOS Process and Thread Concepts
OS Process and Thread Concepts
sgpraju
 
Real time operating systems (rtos) concepts 1
Real time operating systems (rtos) concepts 1Real time operating systems (rtos) concepts 1
Real time operating systems (rtos) concepts 1
Abu Bakr Ramadan
 
Deadlock
DeadlockDeadlock
Deadlock
Sajan Sahu
 
The Linux Block Layer - Built for Fast Storage
The Linux Block Layer - Built for Fast StorageThe Linux Block Layer - Built for Fast Storage
The Linux Block Layer - Built for Fast Storage
Kernel TLV
 
HAProxy TCP 모드에서 내부 서버로 Source IP 전달 방법
HAProxy TCP 모드에서 내부 서버로 Source IP 전달 방법HAProxy TCP 모드에서 내부 서버로 Source IP 전달 방법
HAProxy TCP 모드에서 내부 서버로 Source IP 전달 방법
Young D
 
Linux Performance Analysis: New Tools and Old Secrets
Linux Performance Analysis: New Tools and Old SecretsLinux Performance Analysis: New Tools and Old Secrets
Linux Performance Analysis: New Tools and Old Secrets
Brendan Gregg
 
Embedded Operating System - Linux
Embedded Operating System - LinuxEmbedded Operating System - Linux
Embedded Operating System - Linux
Emertxe Information Technologies Pvt Ltd
 
Mastering Real-time Linux
Mastering Real-time LinuxMastering Real-time Linux
Mastering Real-time Linux
Jean-François Deverge
 
The Linux Kernel Scheduler (For Beginners) - SFO17-421
The Linux Kernel Scheduler (For Beginners) - SFO17-421The Linux Kernel Scheduler (For Beginners) - SFO17-421
The Linux Kernel Scheduler (For Beginners) - SFO17-421
Linaro
 
Linux Internals - Part I
Linux Internals - Part ILinux Internals - Part I
USENIX ATC 2017: Visualizing Performance with Flame Graphs
USENIX ATC 2017: Visualizing Performance with Flame GraphsUSENIX ATC 2017: Visualizing Performance with Flame Graphs
USENIX ATC 2017: Visualizing Performance with Flame Graphs
Brendan Gregg
 
Linux Internals - Kernel/Core
Linux Internals - Kernel/CoreLinux Internals - Kernel/Core
Linux Internals - Kernel/Core
Shay Cohen
 
Introduction to char device driver
Introduction to char device driverIntroduction to char device driver
Introduction to char device driver
Vandana Salve
 
Making Linux do Hard Real-time
Making Linux do Hard Real-timeMaking Linux do Hard Real-time
Making Linux do Hard Real-time
National Cheng Kung University
 
Yet another introduction to Linux RCU
Yet another introduction to Linux RCUYet another introduction to Linux RCU
Yet another introduction to Linux RCU
Viller Hsiao
 
NUSE (Network Stack in Userspace) at #osio
NUSE (Network Stack in Userspace) at #osioNUSE (Network Stack in Userspace) at #osio
NUSE (Network Stack in Userspace) at #osio
Hajime Tazaki
 
From distributed caches to in-memory data grids
From distributed caches to in-memory data gridsFrom distributed caches to in-memory data grids
From distributed caches to in-memory data grids
Max Alexejev
 
Producer Performance Tuning for Apache Kafka
Producer Performance Tuning for Apache KafkaProducer Performance Tuning for Apache Kafka
Producer Performance Tuning for Apache Kafka
Jiangjie Qin
 
Introduction to OpenMP
Introduction to OpenMPIntroduction to OpenMP
Introduction to OpenMP
Akhila Prabhakaran
 

What's hot (20)

6 cpu scheduling
6 cpu scheduling6 cpu scheduling
6 cpu scheduling
 
OS Process and Thread Concepts
OS Process and Thread ConceptsOS Process and Thread Concepts
OS Process and Thread Concepts
 
Real time operating systems (rtos) concepts 1
Real time operating systems (rtos) concepts 1Real time operating systems (rtos) concepts 1
Real time operating systems (rtos) concepts 1
 
Deadlock
DeadlockDeadlock
Deadlock
 
The Linux Block Layer - Built for Fast Storage
The Linux Block Layer - Built for Fast StorageThe Linux Block Layer - Built for Fast Storage
The Linux Block Layer - Built for Fast Storage
 
HAProxy TCP 모드에서 내부 서버로 Source IP 전달 방법
HAProxy TCP 모드에서 내부 서버로 Source IP 전달 방법HAProxy TCP 모드에서 내부 서버로 Source IP 전달 방법
HAProxy TCP 모드에서 내부 서버로 Source IP 전달 방법
 
Linux Performance Analysis: New Tools and Old Secrets
Linux Performance Analysis: New Tools and Old SecretsLinux Performance Analysis: New Tools and Old Secrets
Linux Performance Analysis: New Tools and Old Secrets
 
Embedded Operating System - Linux
Embedded Operating System - LinuxEmbedded Operating System - Linux
Embedded Operating System - Linux
 
Mastering Real-time Linux
Mastering Real-time LinuxMastering Real-time Linux
Mastering Real-time Linux
 
The Linux Kernel Scheduler (For Beginners) - SFO17-421
The Linux Kernel Scheduler (For Beginners) - SFO17-421The Linux Kernel Scheduler (For Beginners) - SFO17-421
The Linux Kernel Scheduler (For Beginners) - SFO17-421
 
Linux Internals - Part I
Linux Internals - Part ILinux Internals - Part I
Linux Internals - Part I
 
USENIX ATC 2017: Visualizing Performance with Flame Graphs
USENIX ATC 2017: Visualizing Performance with Flame GraphsUSENIX ATC 2017: Visualizing Performance with Flame Graphs
USENIX ATC 2017: Visualizing Performance with Flame Graphs
 
Linux Internals - Kernel/Core
Linux Internals - Kernel/CoreLinux Internals - Kernel/Core
Linux Internals - Kernel/Core
 
Introduction to char device driver
Introduction to char device driverIntroduction to char device driver
Introduction to char device driver
 
Making Linux do Hard Real-time
Making Linux do Hard Real-timeMaking Linux do Hard Real-time
Making Linux do Hard Real-time
 
Yet another introduction to Linux RCU
Yet another introduction to Linux RCUYet another introduction to Linux RCU
Yet another introduction to Linux RCU
 
NUSE (Network Stack in Userspace) at #osio
NUSE (Network Stack in Userspace) at #osioNUSE (Network Stack in Userspace) at #osio
NUSE (Network Stack in Userspace) at #osio
 
From distributed caches to in-memory data grids
From distributed caches to in-memory data gridsFrom distributed caches to in-memory data grids
From distributed caches to in-memory data grids
 
Producer Performance Tuning for Apache Kafka
Producer Performance Tuning for Apache KafkaProducer Performance Tuning for Apache Kafka
Producer Performance Tuning for Apache Kafka
 
Introduction to OpenMP
Introduction to OpenMPIntroduction to OpenMP
Introduction to OpenMP
 

Viewers also liked

Multithreading In Java
Multithreading In JavaMultithreading In Java
Multithreading In Java
parag
 
Java multi threading
Java multi threadingJava multi threading
Java multi threading
Raja Sekhar
 
Threads in JAVA
Threads in JAVAThreads in JAVA
Multithreading in java
Multithreading in javaMultithreading in java
Multithreading in java
Raghu nath
 
Java concurrency
Java concurrencyJava concurrency
Java concurrency
ducquoc_vn
 
Java Multi Thead Programming
Java Multi Thead ProgrammingJava Multi Thead Programming
Java Multi Thead Programming
Nishant Mevawala
 
Java Concurrency in Practice
Java Concurrency in PracticeJava Concurrency in Practice
Java Concurrency in Practice
Alina Dolgikh
 
Java And Multithreading
Java And MultithreadingJava And Multithreading
Java And Multithreading
Shraddha
 
Java concurrency in practice
Java concurrency in practiceJava concurrency in practice
Java concurrency in practice
Mikalai Alimenkou
 
Design Patterns & JDK Examples
Design Patterns & JDK ExamplesDesign Patterns & JDK Examples
Design Patterns & JDK Examples
Ender Aydin Orak
 
Threads concept in java
Threads concept in javaThreads concept in java
Threads concept in java
Muthukumaran Subramanian
 
Multithread Programing in Java
Multithread Programing in JavaMultithread Programing in Java
Multithread Programing in Java
M. Raihan
 
Java Multithreading and Concurrency
Java Multithreading and ConcurrencyJava Multithreading and Concurrency
Java Multithreading and Concurrency
Rajesh Ananda Kumar
 
Java Thread Synchronization
Java Thread SynchronizationJava Thread Synchronization
Java Thread Synchronization
Benj Del Mundo
 
Java concurrency
Java concurrencyJava concurrency
Java concurrency
Abhijit Gaikwad
 
Java concurrency begining
Java concurrency   beginingJava concurrency   begining
Java concurrency begining
maksym220889
 
java Unit4 chapter1 applets
java Unit4 chapter1 appletsjava Unit4 chapter1 applets
java Unit4 chapter1 applets
raksharao
 
THREADS EM JAVA: INTRODUÇÃO
THREADS EM JAVA: INTRODUÇÃOTHREADS EM JAVA: INTRODUÇÃO
THREADS EM JAVA: INTRODUÇÃO
ETEC Monsenhor Antonio Magliano
 
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
 
Java Concurrency Gotchas
Java Concurrency GotchasJava Concurrency Gotchas
Java Concurrency Gotchas
Alex Miller
 

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

Similar to Java Course 10: Threads and Concurrency

Java Threads: Lightweight Processes
Java Threads: Lightweight ProcessesJava Threads: Lightweight Processes
Java Threads: Lightweight Processes
Isuru Perera
 
Programming with Threads in Java
Programming with Threads in JavaProgramming with Threads in Java
Programming with Threads in Java
koji lin
 
1.17 Thread in java.pptx
1.17 Thread in java.pptx1.17 Thread in java.pptx
1.17 Thread in java.pptx
TREXSHyNE
 
Threading in java - a pragmatic primer
Threading in java - a pragmatic primerThreading in java - a pragmatic primer
Threading in java - a pragmatic primer
SivaRamaSundar Devasubramaniam
 
Internet Programming with Java
Internet Programming with JavaInternet Programming with Java
Internet Programming with Java
kavitha muneeshwaran
 
Java
JavaJava
Java unit 12
Java unit 12Java unit 12
Java unit 12
Shipra Swati
 
Multithreading programming in java
Multithreading programming in javaMultithreading programming in java
Multithreading programming in java
Elizabeth alexander
 
Java Course 9: Networking and Reflection
Java Course 9: Networking and ReflectionJava Course 9: Networking and Reflection
Java Course 9: Networking and Reflection
Anton Keks
 
Multithreading in java
Multithreading in javaMultithreading in java
Multithreading in java
Kavitha713564
 
Multithreading in java
Multithreading in javaMultithreading in java
Multithreading in java
Kavitha713564
 
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 language
arnavytstudio2814
 
Java Thread
Java ThreadJava Thread
Java Thread
DeeptiJava
 
Basics of Java Concurrency
Basics of Java ConcurrencyBasics of Java Concurrency
Basics of Java Concurrency
kshanth2101
 
Java Course 3: OOP
Java Course 3: OOPJava Course 3: OOP
Java Course 3: OOP
Anton Keks
 
Java Course 4: Exceptions & Collections
Java Course 4: Exceptions & CollectionsJava Course 4: Exceptions & Collections
Java Course 4: Exceptions & Collections
Anton Keks
 
Chap2 2 1
Chap2 2 1Chap2 2 1
Chap2 2 1
Hemo Chella
 
Threads in Java
Threads in JavaThreads in Java
Threads in Java
HarshaDokula
 
Java-Threads And Concurrency Presentation. 2024
Java-Threads And Concurrency Presentation. 2024Java-Threads And Concurrency Presentation. 2024
Java-Threads And Concurrency Presentation. 2024
nehakumari0xf
 

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

Being a professional software tester
Being a professional software testerBeing a professional software tester
Being a professional software tester
Anton Keks
 
Java Course 14: Beans, Applets, GUI
Java Course 14: Beans, Applets, GUIJava Course 14: Beans, Applets, GUI
Java Course 14: Beans, Applets, GUI
Anton Keks
 
Java Course 13: JDBC & Logging
Java Course 13: JDBC & LoggingJava Course 13: JDBC & Logging
Java Course 13: JDBC & Logging
Anton 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 & Servlets
Anton Keks
 
Java Course 11: Design Patterns
Java Course 11: Design PatternsJava Course 11: Design Patterns
Java Course 11: Design Patterns
Anton 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 Streams
Anton 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 & Encodings
Anton Keks
 
Java Course 6: Introduction to Agile
Java Course 6: Introduction to AgileJava Course 6: Introduction to Agile
Java Course 6: Introduction to Agile
Anton Keks
 
Java Course 5: Enums, Generics, Assertions
Java Course 5: Enums, Generics, AssertionsJava Course 5: Enums, Generics, Assertions
Java Course 5: Enums, Generics, Assertions
Anton Keks
 
Java Course 2: Basics
Java Course 2: BasicsJava Course 2: Basics
Java Course 2: Basics
Anton Keks
 
Java Course 1: Introduction
Java Course 1: IntroductionJava Course 1: Introduction
Java Course 1: Introduction
Anton 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, Hibernate
Anton Keks
 
Choose a pattern for a problem
Choose a pattern for a problemChoose a pattern for a problem
Choose a pattern for a problem
Anton Keks
 
Simple Pure Java
Simple Pure JavaSimple Pure Java
Simple Pure Java
Anton Keks
 
Database Refactoring
Database RefactoringDatabase Refactoring
Database Refactoring
Anton 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 engineer
Anton Keks
 
Being a Professional Software Developer
Being a Professional Software DeveloperBeing a Professional Software Developer
Being a Professional Software Developer
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

(CISOPlatform Summit & SACON 2024) Digital Personal Data Protection Act.pdf
(CISOPlatform Summit & SACON 2024) Digital Personal Data Protection Act.pdf(CISOPlatform Summit & SACON 2024) Digital Personal Data Protection Act.pdf
(CISOPlatform Summit & SACON 2024) Digital Personal Data Protection Act.pdf
Priyanka Aash
 
EuroPython 2024 - Streamlining Testing in a Large Python Codebase
EuroPython 2024 - Streamlining Testing in a Large Python CodebaseEuroPython 2024 - Streamlining Testing in a Large Python Codebase
EuroPython 2024 - Streamlining Testing in a Large Python Codebase
Jimmy Lai
 
Acumatica vs. Sage Intacct vs. NetSuite _ NOW CFO.pdf
Acumatica vs. Sage Intacct vs. NetSuite _ NOW CFO.pdfAcumatica vs. Sage Intacct vs. NetSuite _ NOW CFO.pdf
Acumatica vs. Sage Intacct vs. NetSuite _ NOW CFO.pdf
BrainSell Technologies
 
Litestack talk at Brighton 2024 (Unleashing the power of SQLite for Ruby apps)
Litestack talk at Brighton 2024 (Unleashing the power of SQLite for Ruby apps)Litestack talk at Brighton 2024 (Unleashing the power of SQLite for Ruby apps)
Litestack talk at Brighton 2024 (Unleashing the power of SQLite for Ruby apps)
Muhammad Ali
 
Premium Girls Call Mumbai 9920725232 Unlimited Short Providing Girls Service ...
Premium Girls Call Mumbai 9920725232 Unlimited Short Providing Girls Service ...Premium Girls Call Mumbai 9920725232 Unlimited Short Providing Girls Service ...
Premium Girls Call Mumbai 9920725232 Unlimited Short Providing Girls Service ...
shanihomely
 
Computer HARDWARE presenattion by CWD students class 10
Computer HARDWARE presenattion by CWD students class 10Computer HARDWARE presenattion by CWD students class 10
Computer HARDWARE presenattion by CWD students class 10
ankush9927
 
IPLOOK Remote-Sensing Satellite Solution
IPLOOK Remote-Sensing Satellite SolutionIPLOOK Remote-Sensing Satellite Solution
IPLOOK Remote-Sensing Satellite Solution
IPLOOK Networks
 
TrustArc Webinar - 2024 Data Privacy Trends: A Mid-Year Check-In
TrustArc Webinar - 2024 Data Privacy Trends: A Mid-Year Check-InTrustArc Webinar - 2024 Data Privacy Trends: A Mid-Year Check-In
TrustArc Webinar - 2024 Data Privacy Trends: A Mid-Year Check-In
TrustArc
 
High Profile Girls call Service Pune 000XX00000 Provide Best And Top Girl Ser...
High Profile Girls call Service Pune 000XX00000 Provide Best And Top Girl Ser...High Profile Girls call Service Pune 000XX00000 Provide Best And Top Girl Ser...
High Profile Girls call Service Pune 000XX00000 Provide Best And Top Girl Ser...
bhumivarma35300
 
Uncharted Together- Navigating AI's New Frontiers in Libraries
Uncharted Together- Navigating AI's New Frontiers in LibrariesUncharted Together- Navigating AI's New Frontiers in Libraries
Uncharted Together- Navigating AI's New Frontiers in Libraries
Brian Pichman
 
(CISOPlatform Summit & SACON 2024) Keynote _ Power Digital Identities With AI...
(CISOPlatform Summit & SACON 2024) Keynote _ Power Digital Identities With AI...(CISOPlatform Summit & SACON 2024) Keynote _ Power Digital Identities With AI...
(CISOPlatform Summit & SACON 2024) Keynote _ Power Digital Identities With AI...
Priyanka Aash
 
Connector Corner: Leveraging Snowflake Integration for Smarter Decision Making
Connector Corner: Leveraging Snowflake Integration for Smarter Decision MakingConnector Corner: Leveraging Snowflake Integration for Smarter Decision Making
Connector Corner: Leveraging Snowflake Integration for Smarter Decision Making
DianaGray10
 
Types of Weaving loom machine & it's technology
Types of Weaving loom machine & it's technologyTypes of Weaving loom machine & it's technology
Types of Weaving loom machine & it's technology
ldtexsolbl
 
The importance of Quality Assurance for ICT Standardization
The importance of Quality Assurance for ICT StandardizationThe importance of Quality Assurance for ICT Standardization
The importance of Quality Assurance for ICT Standardization
Axel Rennoch
 
Three New Criminal Laws in India 1 July 2024
Three New Criminal Laws in India 1 July 2024Three New Criminal Laws in India 1 July 2024
Three New Criminal Laws in India 1 July 2024
aakash malhotra
 
Use Cases & Benefits of RPA in Manufacturing in 2024.pptx
Use Cases & Benefits of RPA in Manufacturing in 2024.pptxUse Cases & Benefits of RPA in Manufacturing in 2024.pptx
Use Cases & Benefits of RPA in Manufacturing in 2024.pptx
SynapseIndia
 
(CISOPlatform Summit & SACON 2024) Gen AI & Deepfake In Overall Security.pdf
(CISOPlatform Summit & SACON 2024) Gen AI & Deepfake In Overall Security.pdf(CISOPlatform Summit & SACON 2024) Gen AI & Deepfake In Overall Security.pdf
(CISOPlatform Summit & SACON 2024) Gen AI & Deepfake In Overall Security.pdf
Priyanka Aash
 
BT & Neo4j: Knowledge Graphs for Critical Enterprise Systems.pptx.pdf
BT & Neo4j: Knowledge Graphs for Critical Enterprise Systems.pptx.pdfBT & Neo4j: Knowledge Graphs for Critical Enterprise Systems.pptx.pdf
BT & Neo4j: Knowledge Graphs for Critical Enterprise Systems.pptx.pdf
Neo4j
 
Integrating Kafka with MuleSoft 4 and usecase
Integrating Kafka with MuleSoft 4 and usecaseIntegrating Kafka with MuleSoft 4 and usecase
Integrating Kafka with MuleSoft 4 and usecase
shyamraj55
 
(CISOPlatform Summit & SACON 2024) Cyber Insurance & Risk Quantification.pdf
(CISOPlatform Summit & SACON 2024) Cyber Insurance & Risk Quantification.pdf(CISOPlatform Summit & SACON 2024) Cyber Insurance & Risk Quantification.pdf
(CISOPlatform Summit & SACON 2024) Cyber Insurance & Risk Quantification.pdf
Priyanka Aash
 

Recently uploaded (20)

(CISOPlatform Summit & SACON 2024) Digital Personal Data Protection Act.pdf
(CISOPlatform Summit & SACON 2024) Digital Personal Data Protection Act.pdf(CISOPlatform Summit & SACON 2024) Digital Personal Data Protection Act.pdf
(CISOPlatform Summit & SACON 2024) Digital Personal Data Protection Act.pdf
 
EuroPython 2024 - Streamlining Testing in a Large Python Codebase
EuroPython 2024 - Streamlining Testing in a Large Python CodebaseEuroPython 2024 - Streamlining Testing in a Large Python Codebase
EuroPython 2024 - Streamlining Testing in a Large Python Codebase
 
Acumatica vs. Sage Intacct vs. NetSuite _ NOW CFO.pdf
Acumatica vs. Sage Intacct vs. NetSuite _ NOW CFO.pdfAcumatica vs. Sage Intacct vs. NetSuite _ NOW CFO.pdf
Acumatica vs. Sage Intacct vs. NetSuite _ NOW CFO.pdf
 
Litestack talk at Brighton 2024 (Unleashing the power of SQLite for Ruby apps)
Litestack talk at Brighton 2024 (Unleashing the power of SQLite for Ruby apps)Litestack talk at Brighton 2024 (Unleashing the power of SQLite for Ruby apps)
Litestack talk at Brighton 2024 (Unleashing the power of SQLite for Ruby apps)
 
Premium Girls Call Mumbai 9920725232 Unlimited Short Providing Girls Service ...
Premium Girls Call Mumbai 9920725232 Unlimited Short Providing Girls Service ...Premium Girls Call Mumbai 9920725232 Unlimited Short Providing Girls Service ...
Premium Girls Call Mumbai 9920725232 Unlimited Short Providing Girls Service ...
 
Computer HARDWARE presenattion by CWD students class 10
Computer HARDWARE presenattion by CWD students class 10Computer HARDWARE presenattion by CWD students class 10
Computer HARDWARE presenattion by CWD students class 10
 
IPLOOK Remote-Sensing Satellite Solution
IPLOOK Remote-Sensing Satellite SolutionIPLOOK Remote-Sensing Satellite Solution
IPLOOK Remote-Sensing Satellite Solution
 
TrustArc Webinar - 2024 Data Privacy Trends: A Mid-Year Check-In
TrustArc Webinar - 2024 Data Privacy Trends: A Mid-Year Check-InTrustArc Webinar - 2024 Data Privacy Trends: A Mid-Year Check-In
TrustArc Webinar - 2024 Data Privacy Trends: A Mid-Year Check-In
 
High Profile Girls call Service Pune 000XX00000 Provide Best And Top Girl Ser...
High Profile Girls call Service Pune 000XX00000 Provide Best And Top Girl Ser...High Profile Girls call Service Pune 000XX00000 Provide Best And Top Girl Ser...
High Profile Girls call Service Pune 000XX00000 Provide Best And Top Girl Ser...
 
Uncharted Together- Navigating AI's New Frontiers in Libraries
Uncharted Together- Navigating AI's New Frontiers in LibrariesUncharted Together- Navigating AI's New Frontiers in Libraries
Uncharted Together- Navigating AI's New Frontiers in Libraries
 
(CISOPlatform Summit & SACON 2024) Keynote _ Power Digital Identities With AI...
(CISOPlatform Summit & SACON 2024) Keynote _ Power Digital Identities With AI...(CISOPlatform Summit & SACON 2024) Keynote _ Power Digital Identities With AI...
(CISOPlatform Summit & SACON 2024) Keynote _ Power Digital Identities With AI...
 
Connector Corner: Leveraging Snowflake Integration for Smarter Decision Making
Connector Corner: Leveraging Snowflake Integration for Smarter Decision MakingConnector Corner: Leveraging Snowflake Integration for Smarter Decision Making
Connector Corner: Leveraging Snowflake Integration for Smarter Decision Making
 
Types of Weaving loom machine & it's technology
Types of Weaving loom machine & it's technologyTypes of Weaving loom machine & it's technology
Types of Weaving loom machine & it's technology
 
The importance of Quality Assurance for ICT Standardization
The importance of Quality Assurance for ICT StandardizationThe importance of Quality Assurance for ICT Standardization
The importance of Quality Assurance for ICT Standardization
 
Three New Criminal Laws in India 1 July 2024
Three New Criminal Laws in India 1 July 2024Three New Criminal Laws in India 1 July 2024
Three New Criminal Laws in India 1 July 2024
 
Use Cases & Benefits of RPA in Manufacturing in 2024.pptx
Use Cases & Benefits of RPA in Manufacturing in 2024.pptxUse Cases & Benefits of RPA in Manufacturing in 2024.pptx
Use Cases & Benefits of RPA in Manufacturing in 2024.pptx
 
(CISOPlatform Summit & SACON 2024) Gen AI & Deepfake In Overall Security.pdf
(CISOPlatform Summit & SACON 2024) Gen AI & Deepfake In Overall Security.pdf(CISOPlatform Summit & SACON 2024) Gen AI & Deepfake In Overall Security.pdf
(CISOPlatform Summit & SACON 2024) Gen AI & Deepfake In Overall Security.pdf
 
BT & Neo4j: Knowledge Graphs for Critical Enterprise Systems.pptx.pdf
BT & Neo4j: Knowledge Graphs for Critical Enterprise Systems.pptx.pdfBT & Neo4j: Knowledge Graphs for Critical Enterprise Systems.pptx.pdf
BT & Neo4j: Knowledge Graphs for Critical Enterprise Systems.pptx.pdf
 
Integrating Kafka with MuleSoft 4 and usecase
Integrating Kafka with MuleSoft 4 and usecaseIntegrating Kafka with MuleSoft 4 and usecase
Integrating Kafka with MuleSoft 4 and usecase
 
(CISOPlatform Summit & SACON 2024) Cyber Insurance & Risk Quantification.pdf
(CISOPlatform Summit & SACON 2024) Cyber Insurance & Risk Quantification.pdf(CISOPlatform Summit & SACON 2024) Cyber Insurance & Risk Quantification.pdf
(CISOPlatform Summit & SACON 2024) Cyber Insurance & Risk Quantification.pdf
 

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