SlideShare una empresa de Scribd logo
1 de 16
Descargar para leer sin conexión
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

Más contenido relacionado

La actualidad más candente

Mongoose: MongoDB object modelling for Node.js
Mongoose: MongoDB object modelling for Node.jsMongoose: MongoDB object modelling for Node.js
Mongoose: MongoDB object modelling for Node.jsYuriy Bogomolov
 
Spring Framework - MVC
Spring Framework - MVCSpring Framework - MVC
Spring Framework - MVCDzmitry Naskou
 
PUC SE Day 2019 - SpringBoot
PUC SE Day 2019 - SpringBootPUC SE Day 2019 - SpringBoot
PUC SE Day 2019 - SpringBootJosué Neis
 
Web engineering - MVC
Web engineering - MVCWeb engineering - MVC
Web engineering - MVCNosheen Qamar
 
Workshop spring session 2 - La persistance au sein des applications Java
Workshop spring   session 2 - La persistance au sein des applications JavaWorkshop spring   session 2 - La persistance au sein des applications Java
Workshop spring session 2 - La persistance au sein des applications JavaAntoine Rey
 
Spring framework-tutorial
Spring framework-tutorialSpring framework-tutorial
Spring framework-tutorialvinayiqbusiness
 
Asynchronous Programming in C# - Part 1
Asynchronous Programming in C# - Part 1Asynchronous Programming in C# - Part 1
Asynchronous Programming in C# - Part 1Mindfire Solutions
 
Chapter 3 servlet & jsp
Chapter 3 servlet & jspChapter 3 servlet & jsp
Chapter 3 servlet & jspJafar Nesargi
 
Making Java more dynamic: runtime code generation for the JVM
Making Java more dynamic: runtime code generation for the JVMMaking Java more dynamic: runtime code generation for the JVM
Making Java more dynamic: runtime code generation for the JVMRafael Winterhalter
 
Enumeration in Java Explained | Java Tutorial | Edureka
Enumeration in Java Explained | Java Tutorial | EdurekaEnumeration in Java Explained | Java Tutorial | Edureka
Enumeration in Java Explained | Java Tutorial | EdurekaEdureka!
 
Php pattern matching
Php pattern matchingPhp pattern matching
Php pattern matchingJIGAR MAKHIJA
 

La actualidad más candente (20)

Spring Web MVC
Spring Web MVCSpring Web MVC
Spring Web MVC
 
Mongoose: MongoDB object modelling for Node.js
Mongoose: MongoDB object modelling for Node.jsMongoose: MongoDB object modelling for Node.js
Mongoose: MongoDB object modelling for Node.js
 
Spring Framework - MVC
Spring Framework - MVCSpring Framework - MVC
Spring Framework - MVC
 
PUC SE Day 2019 - SpringBoot
PUC SE Day 2019 - SpringBootPUC SE Day 2019 - SpringBoot
PUC SE Day 2019 - SpringBoot
 
Spring Boot
Spring BootSpring Boot
Spring Boot
 
Java threading
Java threadingJava threading
Java threading
 
Inside the jvm
Inside the jvmInside the jvm
Inside the jvm
 
Spring Boot
Spring BootSpring Boot
Spring Boot
 
Web engineering - MVC
Web engineering - MVCWeb engineering - MVC
Web engineering - MVC
 
Workshop spring session 2 - La persistance au sein des applications Java
Workshop spring   session 2 - La persistance au sein des applications JavaWorkshop spring   session 2 - La persistance au sein des applications Java
Workshop spring session 2 - La persistance au sein des applications Java
 
Spring framework-tutorial
Spring framework-tutorialSpring framework-tutorial
Spring framework-tutorial
 
Spring MVC Framework
Spring MVC FrameworkSpring MVC Framework
Spring MVC Framework
 
Hibernate jpa
Hibernate jpaHibernate jpa
Hibernate jpa
 
Asynchronous Programming in C# - Part 1
Asynchronous Programming in C# - Part 1Asynchronous Programming in C# - Part 1
Asynchronous Programming in C# - Part 1
 
Spring mvc
Spring mvcSpring mvc
Spring mvc
 
JNDI
JNDIJNDI
JNDI
 
Chapter 3 servlet & jsp
Chapter 3 servlet & jspChapter 3 servlet & jsp
Chapter 3 servlet & jsp
 
Making Java more dynamic: runtime code generation for the JVM
Making Java more dynamic: runtime code generation for the JVMMaking Java more dynamic: runtime code generation for the JVM
Making Java more dynamic: runtime code generation for the JVM
 
Enumeration in Java Explained | Java Tutorial | Edureka
Enumeration in Java Explained | Java Tutorial | EdurekaEnumeration in Java Explained | Java Tutorial | Edureka
Enumeration in Java Explained | Java Tutorial | Edureka
 
Php pattern matching
Php pattern matchingPhp pattern matching
Php pattern matching
 

Destacado

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 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 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
 
GPars: Groovy Parallelism for Java
GPars: Groovy Parallelism for JavaGPars: Groovy Parallelism for Java
GPars: Groovy Parallelism for JavaRussel Winder
 
Lecture on Java Concurrency Day 4 on Feb 18, 2009.
Lecture on Java Concurrency Day 4 on Feb 18, 2009.Lecture on Java Concurrency Day 4 on Feb 18, 2009.
Lecture on Java Concurrency Day 4 on Feb 18, 2009.Kyung Koo Yoon
 

Destacado (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 concurrency in practice
Java concurrency in practiceJava concurrency in practice
Java concurrency in practice
 
Design Patterns & JDK Examples
Design Patterns & JDK ExamplesDesign Patterns & JDK Examples
Design Patterns & JDK Examples
 
Threads concept in java
Threads concept in javaThreads concept in java
Threads concept in java
 
Multithread Programing in Java
Multithread Programing in JavaMultithread Programing in Java
Multithread Programing in Java
 
Java Thread Synchronization
Java Thread SynchronizationJava Thread Synchronization
Java Thread Synchronization
 
Java concurrency
Java concurrencyJava concurrency
Java concurrency
 
Java concurrency begining
Java concurrency   beginingJava concurrency   begining
Java concurrency begining
 
java Unit4 chapter1 applets
java Unit4 chapter1 appletsjava Unit4 chapter1 applets
java Unit4 chapter1 applets
 
THREADS EM JAVA: INTRODUÇÃO
THREADS EM JAVA: INTRODUÇÃOTHREADS EM JAVA: INTRODUÇÃO
THREADS EM JAVA: INTRODUÇÃO
 
Java Colombo: Developing Highly Scalable Apps
Java Colombo: Developing Highly Scalable AppsJava Colombo: Developing Highly Scalable Apps
Java Colombo: Developing Highly Scalable Apps
 
Java Concurrency Gotchas
Java Concurrency GotchasJava Concurrency Gotchas
Java Concurrency Gotchas
 
GPars: Groovy Parallelism for Java
GPars: Groovy Parallelism for JavaGPars: Groovy Parallelism for Java
GPars: Groovy Parallelism for Java
 
Lecture on Java Concurrency Day 4 on Feb 18, 2009.
Lecture on Java Concurrency Day 4 on Feb 18, 2009.Lecture on Java Concurrency Day 4 on Feb 18, 2009.
Lecture on Java Concurrency Day 4 on Feb 18, 2009.
 

Similar a 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. 2024nehakumari0xf
 

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

Más de 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
 

Más de Anton Keks (17)

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

Último

Artificial intelligence in cctv survelliance.pptx
Artificial intelligence in cctv survelliance.pptxArtificial intelligence in cctv survelliance.pptx
Artificial intelligence in cctv survelliance.pptxhariprasad279825
 
WordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your BrandWordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your Brandgvaughan
 
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024BookNet Canada
 
Connect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck PresentationConnect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck PresentationSlibray Presentation
 
Gen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdfGen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdfAddepto
 
Advanced Computer Architecture – An Introduction
Advanced Computer Architecture – An IntroductionAdvanced Computer Architecture – An Introduction
Advanced Computer Architecture – An IntroductionDilum Bandara
 
Developer Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQLDeveloper Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQLScyllaDB
 
DevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache MavenDevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache MavenHervé Boutemy
 
Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!Commit University
 
TeamStation AI System Report LATAM IT Salaries 2024
TeamStation AI System Report LATAM IT Salaries 2024TeamStation AI System Report LATAM IT Salaries 2024
TeamStation AI System Report LATAM IT Salaries 2024Lonnie McRorey
 
The Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and ConsThe Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and ConsPixlogix Infotech
 
Dev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio WebDev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio WebUiPathCommunity
 
CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):comworks
 
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)Mark Simos
 
H2O.ai CEO/Founder: Sri Ambati Keynote at Wells Fargo Day
H2O.ai CEO/Founder: Sri Ambati Keynote at Wells Fargo DayH2O.ai CEO/Founder: Sri Ambati Keynote at Wells Fargo Day
H2O.ai CEO/Founder: Sri Ambati Keynote at Wells Fargo DaySri Ambati
 
SAP Build Work Zone - Overview L2-L3.pptx
SAP Build Work Zone - Overview L2-L3.pptxSAP Build Work Zone - Overview L2-L3.pptx
SAP Build Work Zone - Overview L2-L3.pptxNavinnSomaal
 
Streamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project SetupStreamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project SetupFlorian Wilhelm
 
Vertex AI Gemini Prompt Engineering Tips
Vertex AI Gemini Prompt Engineering TipsVertex AI Gemini Prompt Engineering Tips
Vertex AI Gemini Prompt Engineering TipsMiki Katsuragi
 
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks..."LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...Fwdays
 
What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024Stephanie Beckett
 

Último (20)

Artificial intelligence in cctv survelliance.pptx
Artificial intelligence in cctv survelliance.pptxArtificial intelligence in cctv survelliance.pptx
Artificial intelligence in cctv survelliance.pptx
 
WordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your BrandWordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your Brand
 
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
 
Connect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck PresentationConnect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck Presentation
 
Gen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdfGen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdf
 
Advanced Computer Architecture – An Introduction
Advanced Computer Architecture – An IntroductionAdvanced Computer Architecture – An Introduction
Advanced Computer Architecture – An Introduction
 
Developer Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQLDeveloper Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQL
 
DevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache MavenDevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache Maven
 
Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!
 
TeamStation AI System Report LATAM IT Salaries 2024
TeamStation AI System Report LATAM IT Salaries 2024TeamStation AI System Report LATAM IT Salaries 2024
TeamStation AI System Report LATAM IT Salaries 2024
 
The Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and ConsThe Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and Cons
 
Dev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio WebDev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio Web
 
CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):
 
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
 
H2O.ai CEO/Founder: Sri Ambati Keynote at Wells Fargo Day
H2O.ai CEO/Founder: Sri Ambati Keynote at Wells Fargo DayH2O.ai CEO/Founder: Sri Ambati Keynote at Wells Fargo Day
H2O.ai CEO/Founder: Sri Ambati Keynote at Wells Fargo Day
 
SAP Build Work Zone - Overview L2-L3.pptx
SAP Build Work Zone - Overview L2-L3.pptxSAP Build Work Zone - Overview L2-L3.pptx
SAP Build Work Zone - Overview L2-L3.pptx
 
Streamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project SetupStreamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project Setup
 
Vertex AI Gemini Prompt Engineering Tips
Vertex AI Gemini Prompt Engineering TipsVertex AI Gemini Prompt Engineering Tips
Vertex AI Gemini Prompt Engineering Tips
 
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks..."LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
 
What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024
 

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