SlideShare a Scribd company logo
1 of 51
Download to read offline
Programming with
 Threads in Java
  koji lin@twjug 2012/9/15
java.lang.Thread
Multiple Threads with in the same program can be
scheduled simultaneously on multiple CPUs.
Most modern operating systems treat threads, not
processes, as the basic units of scheduling
  ~Java concurrency in practice
On a computer with multiprocessors, processes or
threads can run on different processors
  ~MSDN Threads and Processes
其實只想講上面兩段
  ,結束(誤)
Thread Basics
Threads are everywhere
●   JVM creates thread for GC
●   AWT, Swing and JavaFX use event dispatch
    thread
●   Timer for deferred tasks
●   Application server handles multiple client
    –   Servlet must be thread-safe
●   RMI
What is Thread?
●   Process
    –   A program in execution
    –   Providing the resources needed to execute a
        program
    –   One process can't access or modify other
        process
What is Thread?
●   Thread
    –   A basic unit of CPU utilization
    –   Lightweight process (LWP)
    –   Multiple threads are executed within a
        process
        ●   Share process's virtual address space
            and system resource
Thread and Process
Benefits of Thread
Multithreading Models
●   User threads
    –   Efficient, flexible
    –   Above the kernel, without kernel support
●   Kernel threads
    –   kernel can assign one thread to each logical core
        in a system
Multithreading Models
●   User Level Threading
    –   Many-to-One(N:1)
    –   Green Threads, GNU Portable Threads
●   Kernel Level Threading
    –   One-to-One(1:1)
    –   FreeBSD, Linux, Windows, Mac, Solaris...
●   Hybrid
    –   Many-to-Many(M:N)
    –   Solaris(before 9), Tru64 Unix
Java on each OS
●   Windows
    –   Native thread(Windows 95/NT)
●   Linux
    –   Native thread since JDK 1.3
    –   LinuxThread, NPTL(Since Red Hat 9)
●   FreeBSD
    –   Native thread since JDK 1.3.1
    –   libpthread(FreeBSD 5.3)
    –   libthr(FreeBSD 7)
How JVM creates thread?
●   Thread.java
    –   Start0 invokes StartThread
●   jvm.cc
    –   VM_ENTRY(void, JVM_StartThread(JNIEnv* env, jobject
        jthread)) invokes JavaThread
●   Thread.cpp
    –   JavaThread::JavaThread invokes os::create_thread
●   os_windows.cpp, os_linux.cpp,
    os_bsd.cpp
    –   Win32 Thread,NPTL, libthr
Does JVM do
something special?
No!!
So, Why Thread in Java?
●   Thread is inescapable feature of Java
●   Take advantage of multiprocessor system
●   Simplify modeling
●   Thread is cheap
●   Don't need to worry about memory
    model in different environment
Risks
●   Safety Hazards
    –   synchronization
●   Liveness Hazards
    –   deadlock
    –   starvation
●   Performance Hazards
    –   context switch
    –   synchronization
Thread safety
●   Behaves correctly when accessed from multiple
    threads, and there is no synchronization or
    coordination on caller
    –   java.text.SimpleDateFormat is not thread safe
    –   Stateless servlet is safe
Race conditions
●   The output is dependent on the sequence or
    timing of other uncontrollable events

    1)
    if(!map.containsKey(key)){
         map.put(key,value);
    }
    2)
    int n;
    int calculate(){
         return n++;
    }
Synchronized
●   Only one thread can execute the block of code
    protected by the same lock at the same time
●   Ensures that each thread entering a
    synchronized block of code sees the effects of
    all previous modifications that were guarded by
    the same lock

    synchronized(object) {
       //do something...
       …
    }
Visibility problem
●   There is no guarantee that the reading thread
    will see a value written by another thread
●   Using lock or volatile variable
Immutability
●   Immutable object is always thread-safe
    –   Its state cannot be modified after construction
    –   All its fields are final
    –   It is properly constructed
        (object doesn't escape during construction)
●   Even when synchronization is not used
    to publish the object reference
Safe publication
●   Objects that are not immutable must be safely
    published
●   A properly constructed object can be safely
    published by:
    –   Initializing an object reference form static initializer
    –   Storing into volatile or AtomicReference
    –   Storing into a final field of properly
        constructed object
    –   Storing into a field properly guarded by
        lock
Java Memory Model(JSR-133)
●   Defines the semantics of multithreaded
    programs
    –   Ensure your program run on all processor
        architecture
●   Happens-before
    –   If no, JVM is free to reorder
●   New guarantees for Volatile
●   Initialization Safety
    –   final
Happens-before
●   Program order
●   Monitor lock
    –   explicit Lock object
●   Volatile variable
    –   AtomicXXX
●   Thread start, termination
●   Interruption
Happens-before
●   Finalizer
●   Some class libraries
    –   Concurrent containers
●   Transitivity
    –   A -> B ,B -> C then A -> C
Volatile
  Map configOptions;
  volatile boolean initialized = false;


  // In Thread A
  configOptions = new HashMap();
  ConfigOptions.put();
  initialized = true;


  // In Thread B
  while (!initialized)
   sleep();
  // use configOptions
Initialization Safety
●   When object is properly constructed, then all
    threads will see the values for its final fields
    that were set in its constructor, regardless of
    whether or not synchronization is used

●   Similar to a happens-before relationship
    between the write of a final field in a
    constructor and the initial load of a
    shared reference to that object in
    another thread
Executor framework
●   If we have lots of tasks with threads, we need
    to consider:
    –   How many thread should we create?
    –   How to stop them?
    –   What happened when a task failed?
Executor framework
●   Executor manages running tasks
    –   Submit a Runnable to be run with
        Executor#execute()
     final ExecutorService executor = ...;

     executor.execute(new Runnable(){
           @Override
           public void run(){
               // do the task
           }
     });
Task cancellation
●   Using interruption
    public class Thread{
         public void interrupt(){}
         public boolean isInterrupted(){}
         public static boolean interrupted(){}
    }

●   Responding to interruption
    –   throw exception again
    –   set interruption status
Non-interruptible block
●   Synchronous Socket IO
    –   Close socket
●   Lock
    –   Using explicit Lock and lockInterruptibly
java.util.concurrent.*
●   Atomic*
●   Lock
    –   ReentrantLock
    –   ReadWrtieLock
●   CountDownLatch
●   Semaphore
●   ConcurrentHashMap
●   Fork/Join (Java SE 7)
Atomic*
●   Lock-free thread-safe on single variable
●   AtomicInteger, AtomicLong, AtomicReference
    , etc.
    –   getAndAdd, addAndGet, incrementAndGet,
        decrementAndGet, compareAndSet, etc.
●   AtomicStampedReference,
    AtomicMarkableReference
    –   ABA problem
Lock
interface Lock {
   void lock();
   void unlock();
   …
}

●   Only one thread can hold a lock at once
●   ReentrantLock
    –   Can be reacquired by same thread
    –   Other threads can't acquire lock until
        has been released same number of
        times has been acquired
ReadWriteLock(1)
●   Readers-writers problem
    –   同時有複數個讀與寫的動作想要執行 , 當有寫入動作
        時,其他讀寫都不能執行;而沒有寫入動作時,則可
        同時執行多個讀取。
●   Writer starvation/Writer preference
●   Fair/Unfair mode
    –   是否依照抵達順序
    –   實作上看似仍會去避免無限期延遲的狀況
ReadWriteLock(2)
●
    Fair - 當 reader 取得 lock 後有 writer 在等待,
    那麼之後的 reader 將會等到該 writer 取得並釋
    放後才能取得。
●
    Unfair - 當 Queue 中沒有 reader 時,行為同上 ;
    但是當新的 reader 到達時,還有 reader 在
    deque ,則新 reader 會跳過等待的
    writer 先執行。 (bug id:6816565)
Semaphore
●   Counting Semaphore
●
    用於管理有限資源存取
    –   例如 Pool
●   acquire(), tryAcquire()
    –   當計數不為 0 時,內部計數減1並允許執行
    –   如果計數為 0 則等待直到計數不為 0
●   release()
    –   內部計數加1
ConcurrentHashMap
●   We love HashMap
    –   An easy to use Key-Value store
●   Some new methods aware concurrency
    –   putIfAbsent
    –   remove(key, value)
    –   replace(key, value)
    –   replace(key, old value, new value)
JDK7 Fork/Join
●   Fine-Grain Parallelism
    1.Divide large task into small tasks
    2.Process each task in separate thread
    3.Join results
●   ForkJoinPool
●   ForkJoinTask
    –   RecursiveTask
    –   RecursiveAction
JDK7 Fork/Join
●   Work Stealing
JDK8 ParallelIterable

    public interface ParallelIterable<T> ... {
          void forEach(Block<? super T> block)...
    ...
    }
●   Based on Fork/Join
●   More elegant with lambda

    users.parallel().forEach( u -> {...});
    users.parallel().sorted( (u1, u2) ->
        u1.name.compareTo(u2.name));
Useful tools
●   ps -eLF
    –   show thread and process information
●   jstack, jcmd
    –   command line, useful on server environment
●   Jconsole, VisualVM
    –   visual tool integrate commands and tools
Is multithreaded
 programming
    hard ?
Yes
More...
●   To utilize multiprocessor, which one is better?
    –   Thread or Process
●   Performance
    –   How many thread is enough? Or only one thread?
●   Other language or platform
    –   Python, Ruby, C, Node.js, .Net, etc.
Reference
●   WIKIPEDIA Thread
    –   http://en.wikipedia.org/wiki/Thread_(computing)
●   Extending the Haskell Foreign Function
    Interface with Concurrency
    –   Simon Marlow, Simon Peyton Jones, and Wolfgang
        Thaller, Haskell workshop 2004.
●   JSR-133
●   http://www.cs.umd.edu/~pugh/java/memoryMod
    el/jsr-133-faq.html#volatile
Reference
●   Java Concurrency in Practice
●   Performance of Multi-Process and Multi-
    ThreadProcessing on Multi-core SMT
    Processors
    –   https://www.research.ibm.com/trl/people/inouehrs/p
        df/IISWC2010_inoue_slides.pdf
●   Java Technology on the Linux Platform
    –   http://java.sun.com/developer/
        technicalArticles/Programming/linux/
●   http://hg.openjdk.java.net/
Reference
●   Java theory and practice: Fixing the Java
    Memory Model, Part 2
    –   http://www.ibm.com/developerworks/library/j-
        jtp03304/
●   Programming with POSIX Threads
●   Kernel Programming Guide(OS X)
    –   https://developer.apple.com/library/mac/#document
        ation/Darwin/Conceptual/KernelProgramming/Mach
        /Mach.html

More Related Content

What's hot

Multithreading In Java
Multithreading In JavaMultithreading In Java
Multithreading In Javaparag
 
Java Thread & Multithreading
Java Thread & MultithreadingJava Thread & Multithreading
Java Thread & Multithreadingjehan1987
 
Java Threads and Concurrency
Java Threads and ConcurrencyJava Threads and Concurrency
Java Threads and ConcurrencySunil OS
 
Thread model of java
Thread model of javaThread model of java
Thread model of javamyrajendra
 
Multithread Programing in Java
Multithread Programing in JavaMultithread Programing in Java
Multithread Programing in JavaM. Raihan
 
Multithreading in-java
Multithreading in-javaMultithreading in-java
Multithreading in-javaaalipalh
 
Advanced Introduction to Java Multi-Threading - Full (chok)
Advanced Introduction to Java Multi-Threading - Full (chok)Advanced Introduction to Java Multi-Threading - Full (chok)
Advanced Introduction to Java Multi-Threading - Full (chok)choksheak
 
Learning Java 3 – Threads and Synchronization
Learning Java 3 – Threads and SynchronizationLearning Java 3 – Threads and Synchronization
Learning Java 3 – Threads and Synchronizationcaswenson
 
Java concurrency
Java concurrencyJava concurrency
Java concurrencyducquoc_vn
 
Java And Multithreading
Java And MultithreadingJava And Multithreading
Java And MultithreadingShraddha
 
Java Course 10: Threads and Concurrency
Java Course 10: Threads and ConcurrencyJava Course 10: Threads and Concurrency
Java Course 10: Threads and ConcurrencyAnton Keks
 
12 multi-threading
12 multi-threading12 multi-threading
12 multi-threadingAPU
 
L22 multi-threading-introduction
L22 multi-threading-introductionL22 multi-threading-introduction
L22 multi-threading-introductionteach4uin
 

What's hot (20)

Multithreading In Java
Multithreading In JavaMultithreading In Java
Multithreading In Java
 
Java Thread & Multithreading
Java Thread & MultithreadingJava Thread & Multithreading
Java Thread & Multithreading
 
Thread model in java
Thread model in javaThread model in java
Thread model in java
 
Java Threads and Concurrency
Java Threads and ConcurrencyJava Threads and Concurrency
Java Threads and Concurrency
 
Multi threading
Multi threadingMulti threading
Multi threading
 
Thread model of java
Thread model of javaThread model of java
Thread model of java
 
Multithread Programing in Java
Multithread Programing in JavaMultithread Programing in Java
Multithread Programing in Java
 
Multithreading in-java
Multithreading in-javaMultithreading in-java
Multithreading in-java
 
Advanced Introduction to Java Multi-Threading - Full (chok)
Advanced Introduction to Java Multi-Threading - Full (chok)Advanced Introduction to Java Multi-Threading - Full (chok)
Advanced Introduction to Java Multi-Threading - Full (chok)
 
Learning Java 3 – Threads and Synchronization
Learning Java 3 – Threads and SynchronizationLearning Java 3 – Threads and Synchronization
Learning Java 3 – Threads and Synchronization
 
Java thread
Java threadJava thread
Java thread
 
Thread
ThreadThread
Thread
 
Java concurrency
Java concurrencyJava concurrency
Java concurrency
 
Java threads
Java threadsJava threads
Java threads
 
Java And Multithreading
Java And MultithreadingJava And Multithreading
Java And Multithreading
 
Java Course 10: Threads and Concurrency
Java Course 10: Threads and ConcurrencyJava Course 10: Threads and Concurrency
Java Course 10: Threads and Concurrency
 
java threads
java threadsjava threads
java threads
 
12 multi-threading
12 multi-threading12 multi-threading
12 multi-threading
 
L22 multi-threading-introduction
L22 multi-threading-introductionL22 multi-threading-introduction
L22 multi-threading-introduction
 
Multithreading in Java
Multithreading in JavaMultithreading in Java
Multithreading in Java
 

Viewers also liked

Exception Handling In Java
Exception Handling In JavaException Handling In Java
Exception Handling In Javaparag
 
Java Exception handling
Java Exception handlingJava Exception handling
Java Exception handlingkamal kotecha
 
Files & IO in Java
Files & IO in JavaFiles & IO in Java
Files & IO in JavaCIB Egypt
 
Unidad 1 MOOC MVC
Unidad 1 MOOC MVCUnidad 1 MOOC MVC
Unidad 1 MOOC MVCscolomina
 
Become a Great Communicator
Become a Great CommunicatorBecome a Great Communicator
Become a Great CommunicatorTony Santiago
 
What We Talk About When We Talk About Unit Testing
What We Talk About When We Talk About Unit TestingWhat We Talk About When We Talk About Unit Testing
What We Talk About When We Talk About Unit TestingKevlin Henney
 
Spoken english classes in kalewadi phata
Spoken english classes in kalewadi phataSpoken english classes in kalewadi phata
Spoken english classes in kalewadi phataRaj Kumar
 
Speak better English here's how.
Speak better English here's how.Speak better English here's how.
Speak better English here's how.James Russell
 
1st qtr 16 use variety of sentences
1st qtr 16 use variety of sentences1st qtr 16 use variety of sentences
1st qtr 16 use variety of sentencesShirley Sison
 
IO In Java
IO In JavaIO In Java
IO In Javaparag
 
Writing code you won't hate tomorrow
Writing code you won't hate tomorrowWriting code you won't hate tomorrow
Writing code you won't hate tomorrowRafael Dohms
 
Design Pattern From Java To Ruby
Design Pattern From Java To RubyDesign Pattern From Java To Ruby
Design Pattern From Java To Rubyyelogic
 
VTU PCD Model Question Paper - Programming in C
VTU PCD Model Question Paper - Programming in CVTU PCD Model Question Paper - Programming in C
VTU PCD Model Question Paper - Programming in CSyed Mustafa
 

Viewers also liked (20)

Spring mvc
Spring mvcSpring mvc
Spring mvc
 
Applet java
Applet javaApplet java
Applet java
 
Exception Handling In Java
Exception Handling In JavaException Handling In Java
Exception Handling In Java
 
Java applets
Java appletsJava applets
Java applets
 
Java Exception handling
Java Exception handlingJava Exception handling
Java Exception handling
 
Thread priorities
Thread prioritiesThread priorities
Thread priorities
 
7th semester VTU BE CS & IS question papers from 2010 to July 2016
7th semester VTU BE CS & IS question papers from 2010 to July 20167th semester VTU BE CS & IS question papers from 2010 to July 2016
7th semester VTU BE CS & IS question papers from 2010 to July 2016
 
Files & IO in Java
Files & IO in JavaFiles & IO in Java
Files & IO in Java
 
Unidad 1 MOOC MVC
Unidad 1 MOOC MVCUnidad 1 MOOC MVC
Unidad 1 MOOC MVC
 
Become a Great Communicator
Become a Great CommunicatorBecome a Great Communicator
Become a Great Communicator
 
What We Talk About When We Talk About Unit Testing
What We Talk About When We Talk About Unit TestingWhat We Talk About When We Talk About Unit Testing
What We Talk About When We Talk About Unit Testing
 
Spoken english classes in kalewadi phata
Spoken english classes in kalewadi phataSpoken english classes in kalewadi phata
Spoken english classes in kalewadi phata
 
Speak better English here's how.
Speak better English here's how.Speak better English here's how.
Speak better English here's how.
 
My History
My HistoryMy History
My History
 
1st qtr 16 use variety of sentences
1st qtr 16 use variety of sentences1st qtr 16 use variety of sentences
1st qtr 16 use variety of sentences
 
Spring mvc
Spring mvcSpring mvc
Spring mvc
 
IO In Java
IO In JavaIO In Java
IO In Java
 
Writing code you won't hate tomorrow
Writing code you won't hate tomorrowWriting code you won't hate tomorrow
Writing code you won't hate tomorrow
 
Design Pattern From Java To Ruby
Design Pattern From Java To RubyDesign Pattern From Java To Ruby
Design Pattern From Java To Ruby
 
VTU PCD Model Question Paper - Programming in C
VTU PCD Model Question Paper - Programming in CVTU PCD Model Question Paper - Programming in C
VTU PCD Model Question Paper - Programming in C
 

Similar to Programming with Threads in Java

Java Threads: Lightweight Processes
Java Threads: Lightweight ProcessesJava Threads: Lightweight Processes
Java Threads: Lightweight ProcessesIsuru Perera
 
Looming Marvelous - Virtual Threads in Java Javaland.pdf
Looming Marvelous - Virtual Threads in Java Javaland.pdfLooming Marvelous - Virtual Threads in Java Javaland.pdf
Looming Marvelous - Virtual Threads in Java Javaland.pdfjexp
 
Java Concurrency in Practice
Java Concurrency in PracticeJava Concurrency in Practice
Java Concurrency in PracticeAlina Dolgikh
 
Introduction to concurrent programming with akka actors
Introduction to concurrent programming with akka actorsIntroduction to concurrent programming with akka actors
Introduction to concurrent programming with akka actorsdatamantra
 
Introduction to concurrent programming with Akka actors
Introduction to concurrent programming with Akka actorsIntroduction to concurrent programming with Akka actors
Introduction to concurrent programming with Akka actorsShashank L
 
Multithreading programming in java
Multithreading programming in javaMultithreading programming in java
Multithreading programming in javaElizabeth alexander
 
Concurrency patterns in Ruby
Concurrency patterns in RubyConcurrency patterns in Ruby
Concurrency patterns in RubyThoughtWorks
 
Concurrency patterns in Ruby
Concurrency patterns in RubyConcurrency patterns in Ruby
Concurrency patterns in RubyThoughtWorks
 
Reactive Software Systems
Reactive Software SystemsReactive Software Systems
Reactive Software SystemsBehrad Zari
 
Concurrent Programming in Java
Concurrent Programming in JavaConcurrent Programming in Java
Concurrent Programming in JavaRuben Inoto Soto
 
Concurrency Learning From Jdk Source
Concurrency Learning From Jdk SourceConcurrency Learning From Jdk Source
Concurrency Learning From Jdk SourceKaniska Mandal
 
Lecture 23-24.pptx
Lecture 23-24.pptxLecture 23-24.pptx
Lecture 23-24.pptxtalha ijaz
 
The art of concurrent programming
The art of concurrent programmingThe art of concurrent programming
The art of concurrent programmingIskren Chernev
 
The State of the Veil Framework
The State of the Veil FrameworkThe State of the Veil Framework
The State of the Veil FrameworkVeilFramework
 
Medical Image Processing Strategies for multi-core CPUs
Medical Image Processing Strategies for multi-core CPUsMedical Image Processing Strategies for multi-core CPUs
Medical Image Processing Strategies for multi-core CPUsDaniel Blezek
 
Modern Java Concurrency
Modern Java ConcurrencyModern Java Concurrency
Modern Java ConcurrencyBen Evans
 
Concurrent/ parallel programming
Concurrent/ parallel programmingConcurrent/ parallel programming
Concurrent/ parallel programmingTausun Akhtary
 

Similar to Programming with Threads in Java (20)

Java Threads: Lightweight Processes
Java Threads: Lightweight ProcessesJava Threads: Lightweight Processes
Java Threads: Lightweight Processes
 
Looming Marvelous - Virtual Threads in Java Javaland.pdf
Looming Marvelous - Virtual Threads in Java Javaland.pdfLooming Marvelous - Virtual Threads in Java Javaland.pdf
Looming Marvelous - Virtual Threads in Java Javaland.pdf
 
Java Concurrency in Practice
Java Concurrency in PracticeJava Concurrency in Practice
Java Concurrency in Practice
 
Introduction to concurrent programming with akka actors
Introduction to concurrent programming with akka actorsIntroduction to concurrent programming with akka actors
Introduction to concurrent programming with akka actors
 
Introduction to concurrent programming with Akka actors
Introduction to concurrent programming with Akka actorsIntroduction to concurrent programming with Akka actors
Introduction to concurrent programming with Akka actors
 
Multithreading programming in java
Multithreading programming in javaMultithreading programming in java
Multithreading programming in java
 
Concurrency patterns in Ruby
Concurrency patterns in RubyConcurrency patterns in Ruby
Concurrency patterns in Ruby
 
Concurrency patterns in Ruby
Concurrency patterns in RubyConcurrency patterns in Ruby
Concurrency patterns in Ruby
 
Concept of thread
Concept of threadConcept of thread
Concept of thread
 
Reactive Software Systems
Reactive Software SystemsReactive Software Systems
Reactive Software Systems
 
Concurrent Programming in Java
Concurrent Programming in JavaConcurrent Programming in Java
Concurrent Programming in Java
 
Concurrency Learning From Jdk Source
Concurrency Learning From Jdk SourceConcurrency Learning From Jdk Source
Concurrency Learning From Jdk Source
 
Java Enterprise Edition
Java Enterprise EditionJava Enterprise Edition
Java Enterprise Edition
 
Lecture 23-24.pptx
Lecture 23-24.pptxLecture 23-24.pptx
Lecture 23-24.pptx
 
The art of concurrent programming
The art of concurrent programmingThe art of concurrent programming
The art of concurrent programming
 
Linux Internals - Part III
Linux Internals - Part IIILinux Internals - Part III
Linux Internals - Part III
 
The State of the Veil Framework
The State of the Veil FrameworkThe State of the Veil Framework
The State of the Veil Framework
 
Medical Image Processing Strategies for multi-core CPUs
Medical Image Processing Strategies for multi-core CPUsMedical Image Processing Strategies for multi-core CPUs
Medical Image Processing Strategies for multi-core CPUs
 
Modern Java Concurrency
Modern Java ConcurrencyModern Java Concurrency
Modern Java Concurrency
 
Concurrent/ parallel programming
Concurrent/ parallel programmingConcurrent/ parallel programming
Concurrent/ parallel programming
 

More from koji lin

サーバーサイドでの非同期処理で色々やったよ
サーバーサイドでの非同期処理で色々やったよサーバーサイドでの非同期処理で色々やったよ
サーバーサイドでの非同期処理で色々やったよkoji lin
 
Using armeria to write your RPC
Using armeria to write your RPCUsing armeria to write your RPC
Using armeria to write your RPCkoji lin
 
使用 Java 上的 future/promise API
使用 Java 上的 future/promise  API使用 Java 上的 future/promise  API
使用 Java 上的 future/promise APIkoji lin
 
Annotation processing and code gen
Annotation processing and code genAnnotation processing and code gen
Annotation processing and code genkoji lin
 
Use Lambdas in Android
Use Lambdas in AndroidUse Lambdas in Android
Use Lambdas in Androidkoji lin
 
docker intro
docker introdocker intro
docker introkoji lin
 
Java8 time
Java8 timeJava8 time
Java8 timekoji lin
 
Java8 stream
Java8 streamJava8 stream
Java8 streamkoji lin
 
Java8 lambda
Java8 lambdaJava8 lambda
Java8 lambdakoji lin
 
CompletableFuture
CompletableFutureCompletableFuture
CompletableFuturekoji lin
 
Raspberry Pi with Java
Raspberry Pi with JavaRaspberry Pi with Java
Raspberry Pi with Javakoji lin
 
Services you can use to monitor and analyze mobile app
Services you can use to monitor and analyze mobile appServices you can use to monitor and analyze mobile app
Services you can use to monitor and analyze mobile appkoji lin
 
山頂洞人日記 - 回歸到最純樸的開發
山頂洞人日記 -  回歸到最純樸的開發山頂洞人日記 -  回歸到最純樸的開發
山頂洞人日記 - 回歸到最純樸的開發koji lin
 
Android Location-based應用開發分享
Android Location-based應用開發分享Android Location-based應用開發分享
Android Location-based應用開發分享koji lin
 

More from koji lin (18)

サーバーサイドでの非同期処理で色々やったよ
サーバーサイドでの非同期処理で色々やったよサーバーサイドでの非同期処理で色々やったよ
サーバーサイドでの非同期処理で色々やったよ
 
G1GC
G1GCG1GC
G1GC
 
Using armeria to write your RPC
Using armeria to write your RPCUsing armeria to write your RPC
Using armeria to write your RPC
 
使用 Java 上的 future/promise API
使用 Java 上的 future/promise  API使用 Java 上的 future/promise  API
使用 Java 上的 future/promise API
 
Annotation processing and code gen
Annotation processing and code genAnnotation processing and code gen
Annotation processing and code gen
 
Jcconf
JcconfJcconf
Jcconf
 
Use Lambdas in Android
Use Lambdas in AndroidUse Lambdas in Android
Use Lambdas in Android
 
docker intro
docker introdocker intro
docker intro
 
Java8 time
Java8 timeJava8 time
Java8 time
 
Java8 stream
Java8 streamJava8 stream
Java8 stream
 
Java8 lambda
Java8 lambdaJava8 lambda
Java8 lambda
 
Idea13
Idea13Idea13
Idea13
 
CompletableFuture
CompletableFutureCompletableFuture
CompletableFuture
 
Raspberry Pi with Java
Raspberry Pi with JavaRaspberry Pi with Java
Raspberry Pi with Java
 
Services you can use to monitor and analyze mobile app
Services you can use to monitor and analyze mobile appServices you can use to monitor and analyze mobile app
Services you can use to monitor and analyze mobile app
 
JQuery
JQueryJQuery
JQuery
 
山頂洞人日記 - 回歸到最純樸的開發
山頂洞人日記 -  回歸到最純樸的開發山頂洞人日記 -  回歸到最純樸的開發
山頂洞人日記 - 回歸到最純樸的開發
 
Android Location-based應用開發分享
Android Location-based應用開發分享Android Location-based應用開發分享
Android Location-based應用開發分享
 

Recently uploaded

08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking MenDelhi Call girls
 
Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024The Digital Insurer
 
Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024The Digital Insurer
 
Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...Enterprise Knowledge
 
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProduct Anonymous
 
Data Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonData Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonAnna Loughnan Colquhoun
 
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...Igalia
 
A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)Gabriella Davis
 
08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking MenDelhi Call girls
 
presentation ICT roal in 21st century education
presentation ICT roal in 21st century educationpresentation ICT roal in 21st century education
presentation ICT roal in 21st century educationjfdjdjcjdnsjd
 
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024The Digital Insurer
 
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptxHampshireHUG
 
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking MenDelhi Call girls
 
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationFrom Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationSafe Software
 
[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdfhans926745
 
GenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationGenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationMichael W. Hawkins
 
Strategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherStrategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherRemote DBA Services
 
2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...Martijn de Jong
 
Boost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityBoost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityPrincipled Technologies
 
IAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsIAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsEnterprise Knowledge
 

Recently uploaded (20)

08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
 
Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024
 
Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024
 
Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...
 
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
 
Data Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonData Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt Robison
 
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
 
A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)
 
08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men
 
presentation ICT roal in 21st century education
presentation ICT roal in 21st century educationpresentation ICT roal in 21st century education
presentation ICT roal in 21st century education
 
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
 
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
 
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
 
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationFrom Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
 
[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf
 
GenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationGenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day Presentation
 
Strategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherStrategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a Fresher
 
2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...
 
Boost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityBoost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivity
 
IAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsIAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI Solutions
 

Programming with Threads in Java

  • 1. Programming with Threads in Java koji lin@twjug 2012/9/15
  • 3. Multiple Threads with in the same program can be scheduled simultaneously on multiple CPUs. Most modern operating systems treat threads, not processes, as the basic units of scheduling ~Java concurrency in practice
  • 4. On a computer with multiprocessors, processes or threads can run on different processors ~MSDN Threads and Processes
  • 7. Threads are everywhere ● JVM creates thread for GC ● AWT, Swing and JavaFX use event dispatch thread ● Timer for deferred tasks ● Application server handles multiple client – Servlet must be thread-safe ● RMI
  • 8. What is Thread? ● Process – A program in execution – Providing the resources needed to execute a program – One process can't access or modify other process
  • 9. What is Thread? ● Thread – A basic unit of CPU utilization – Lightweight process (LWP) – Multiple threads are executed within a process ● Share process's virtual address space and system resource
  • 12. Multithreading Models ● User threads – Efficient, flexible – Above the kernel, without kernel support ● Kernel threads – kernel can assign one thread to each logical core in a system
  • 13. Multithreading Models ● User Level Threading – Many-to-One(N:1) – Green Threads, GNU Portable Threads ● Kernel Level Threading – One-to-One(1:1) – FreeBSD, Linux, Windows, Mac, Solaris... ● Hybrid – Many-to-Many(M:N) – Solaris(before 9), Tru64 Unix
  • 14. Java on each OS ● Windows – Native thread(Windows 95/NT) ● Linux – Native thread since JDK 1.3 – LinuxThread, NPTL(Since Red Hat 9) ● FreeBSD – Native thread since JDK 1.3.1 – libpthread(FreeBSD 5.3) – libthr(FreeBSD 7)
  • 15. How JVM creates thread? ● Thread.java – Start0 invokes StartThread ● jvm.cc – VM_ENTRY(void, JVM_StartThread(JNIEnv* env, jobject jthread)) invokes JavaThread ● Thread.cpp – JavaThread::JavaThread invokes os::create_thread ● os_windows.cpp, os_linux.cpp, os_bsd.cpp – Win32 Thread,NPTL, libthr
  • 17. No!!
  • 18. So, Why Thread in Java? ● Thread is inescapable feature of Java ● Take advantage of multiprocessor system ● Simplify modeling ● Thread is cheap ● Don't need to worry about memory model in different environment
  • 19. Risks ● Safety Hazards – synchronization ● Liveness Hazards – deadlock – starvation ● Performance Hazards – context switch – synchronization
  • 20. Thread safety ● Behaves correctly when accessed from multiple threads, and there is no synchronization or coordination on caller – java.text.SimpleDateFormat is not thread safe – Stateless servlet is safe
  • 21. Race conditions ● The output is dependent on the sequence or timing of other uncontrollable events 1) if(!map.containsKey(key)){ map.put(key,value); } 2) int n; int calculate(){ return n++; }
  • 22. Synchronized ● Only one thread can execute the block of code protected by the same lock at the same time ● Ensures that each thread entering a synchronized block of code sees the effects of all previous modifications that were guarded by the same lock synchronized(object) { //do something... … }
  • 23. Visibility problem ● There is no guarantee that the reading thread will see a value written by another thread ● Using lock or volatile variable
  • 24. Immutability ● Immutable object is always thread-safe – Its state cannot be modified after construction – All its fields are final – It is properly constructed (object doesn't escape during construction) ● Even when synchronization is not used to publish the object reference
  • 25. Safe publication ● Objects that are not immutable must be safely published ● A properly constructed object can be safely published by: – Initializing an object reference form static initializer – Storing into volatile or AtomicReference – Storing into a final field of properly constructed object – Storing into a field properly guarded by lock
  • 26. Java Memory Model(JSR-133) ● Defines the semantics of multithreaded programs – Ensure your program run on all processor architecture ● Happens-before – If no, JVM is free to reorder ● New guarantees for Volatile ● Initialization Safety – final
  • 27. Happens-before ● Program order ● Monitor lock – explicit Lock object ● Volatile variable – AtomicXXX ● Thread start, termination ● Interruption
  • 28. Happens-before ● Finalizer ● Some class libraries – Concurrent containers ● Transitivity – A -> B ,B -> C then A -> C
  • 29. Volatile Map configOptions; volatile boolean initialized = false; // In Thread A configOptions = new HashMap(); ConfigOptions.put(); initialized = true; // In Thread B while (!initialized) sleep(); // use configOptions
  • 30. Initialization Safety ● When object is properly constructed, then all threads will see the values for its final fields that were set in its constructor, regardless of whether or not synchronization is used ● Similar to a happens-before relationship between the write of a final field in a constructor and the initial load of a shared reference to that object in another thread
  • 31. Executor framework ● If we have lots of tasks with threads, we need to consider: – How many thread should we create? – How to stop them? – What happened when a task failed?
  • 32. Executor framework ● Executor manages running tasks – Submit a Runnable to be run with Executor#execute() final ExecutorService executor = ...; executor.execute(new Runnable(){ @Override public void run(){ // do the task } });
  • 33. Task cancellation ● Using interruption public class Thread{ public void interrupt(){} public boolean isInterrupted(){} public static boolean interrupted(){} } ● Responding to interruption – throw exception again – set interruption status
  • 34. Non-interruptible block ● Synchronous Socket IO – Close socket ● Lock – Using explicit Lock and lockInterruptibly
  • 35. java.util.concurrent.* ● Atomic* ● Lock – ReentrantLock – ReadWrtieLock ● CountDownLatch ● Semaphore ● ConcurrentHashMap ● Fork/Join (Java SE 7)
  • 36. Atomic* ● Lock-free thread-safe on single variable ● AtomicInteger, AtomicLong, AtomicReference , etc. – getAndAdd, addAndGet, incrementAndGet, decrementAndGet, compareAndSet, etc. ● AtomicStampedReference, AtomicMarkableReference – ABA problem
  • 37. Lock interface Lock { void lock(); void unlock(); … } ● Only one thread can hold a lock at once ● ReentrantLock – Can be reacquired by same thread – Other threads can't acquire lock until has been released same number of times has been acquired
  • 38. ReadWriteLock(1) ● Readers-writers problem – 同時有複數個讀與寫的動作想要執行 , 當有寫入動作 時,其他讀寫都不能執行;而沒有寫入動作時,則可 同時執行多個讀取。 ● Writer starvation/Writer preference ● Fair/Unfair mode – 是否依照抵達順序 – 實作上看似仍會去避免無限期延遲的狀況
  • 39. ReadWriteLock(2) ● Fair - 當 reader 取得 lock 後有 writer 在等待, 那麼之後的 reader 將會等到該 writer 取得並釋 放後才能取得。 ● Unfair - 當 Queue 中沒有 reader 時,行為同上 ; 但是當新的 reader 到達時,還有 reader 在 deque ,則新 reader 會跳過等待的 writer 先執行。 (bug id:6816565)
  • 40. Semaphore ● Counting Semaphore ● 用於管理有限資源存取 – 例如 Pool ● acquire(), tryAcquire() – 當計數不為 0 時,內部計數減1並允許執行 – 如果計數為 0 則等待直到計數不為 0 ● release() – 內部計數加1
  • 41. ConcurrentHashMap ● We love HashMap – An easy to use Key-Value store ● Some new methods aware concurrency – putIfAbsent – remove(key, value) – replace(key, value) – replace(key, old value, new value)
  • 42. JDK7 Fork/Join ● Fine-Grain Parallelism 1.Divide large task into small tasks 2.Process each task in separate thread 3.Join results ● ForkJoinPool ● ForkJoinTask – RecursiveTask – RecursiveAction
  • 43. JDK7 Fork/Join ● Work Stealing
  • 44. JDK8 ParallelIterable public interface ParallelIterable<T> ... { void forEach(Block<? super T> block)... ... } ● Based on Fork/Join ● More elegant with lambda users.parallel().forEach( u -> {...}); users.parallel().sorted( (u1, u2) -> u1.name.compareTo(u2.name));
  • 45. Useful tools ● ps -eLF – show thread and process information ● jstack, jcmd – command line, useful on server environment ● Jconsole, VisualVM – visual tool integrate commands and tools
  • 47. Yes
  • 48. More... ● To utilize multiprocessor, which one is better? – Thread or Process ● Performance – How many thread is enough? Or only one thread? ● Other language or platform – Python, Ruby, C, Node.js, .Net, etc.
  • 49. Reference ● WIKIPEDIA Thread – http://en.wikipedia.org/wiki/Thread_(computing) ● Extending the Haskell Foreign Function Interface with Concurrency – Simon Marlow, Simon Peyton Jones, and Wolfgang Thaller, Haskell workshop 2004. ● JSR-133 ● http://www.cs.umd.edu/~pugh/java/memoryMod el/jsr-133-faq.html#volatile
  • 50. Reference ● Java Concurrency in Practice ● Performance of Multi-Process and Multi- ThreadProcessing on Multi-core SMT Processors – https://www.research.ibm.com/trl/people/inouehrs/p df/IISWC2010_inoue_slides.pdf ● Java Technology on the Linux Platform – http://java.sun.com/developer/ technicalArticles/Programming/linux/ ● http://hg.openjdk.java.net/
  • 51. Reference ● Java theory and practice: Fixing the Java Memory Model, Part 2 – http://www.ibm.com/developerworks/library/j- jtp03304/ ● Programming with POSIX Threads ● Kernel Programming Guide(OS X) – https://developer.apple.com/library/mac/#document ation/Darwin/Conceptual/KernelProgramming/Mach /Mach.html