SlideShare a Scribd company logo
1 of 31
Java
Thread

           2011 4    9
         twitter: @zaki50
Who am I

•          YAMAZAKI Makoto(twitter: @zaki50)
•   Android

    •
    •   StickyShortcut
•           Java
• Effective Java       2

  • ISBN:978-4-89471-499-1

  • 3,780   (      )

  •      66,       69
Agenda


• synchronized / volatile
• Lock(ReentrantLock)
• java.util.concurrent
synchronized
Eclipse   (jvisualvm)
synchronized
class Sample {
    public synchronized void execute1() {
        //
    }
    public void execute1b() {
        synchronized (this) {
            //
        }
    }
    public static synchronized void execute2() {
        //
    }
    public static synchronized void execute2b() {
        synchronized (Sample.class) {
            //
        }
    }
}
synchronized

•

•

•
•
•
         (by Wikipedia)

• Java       1
    1


                 1
                     1
•

    • synchronized

    • Object#wait()

•

    • synchronized

    • Object#wait()
•
    synchronized



•
synchronized
class Sample {
    public synchronized void execute1() {
        //
    }
    public void execute1b() {
        synchronized (this) {
            //
        }
    }
    public static synchronized void execute2() {
        //
    }
    public static synchronized void execute2b() {
        synchronized (Sample.class) {
            //
        }
    }
}
•
•
• Java VM



    •

    •

•
private static boolean stopRequested = false;
private static int value = 0;

public static void main(String[] args) throws Exception {
    new Thread() {
        @Override
        public void run() {
            int i = 0;
                                                 if (!stopRequested) {
            while (!stopRequested) {                 while (true) {
                i++;                                     i++;
            }
                                                     }
                                                 }
            System.out.println(value);
        }
    }.start();

    TimeUnit.SECONDS.sleep(1L);
    value = 100;
    stopRequested = true;
}
private static boolean stopRequested = false;
private static int value = 0;

public static void main(String[] args) throws Exception {
    new Thread() {
        @Override
        public void run() {
            int i = 0;
            while (!stopped()) {
                i++;
            }
            System.out.println(value);
        }
    }.start();                   private synchronized static void stop() {
                                     stopRequested = true;
    TimeUnit.SECONDS.sleep(1L); }
    value = 100;
    stop();                      private synchronized static boolean stopped() {
}                                    return stopRequested;
                                 }
volatile
volatile

•

• volatile



• volatile
volatile
private volatile static boolean stopRequested = false;
private volatile static int value = 0;

public static void main(String[] args) throws Exception {
    new Thread() {
        @Override
        public void run() {
            int i = 0;

            while (!stopRequested) {
                i++;
            }

            System.out.println(value);
        }
    }.start();

    TimeUnit.SECONDS.sleep(1L);
    value = 100;
    stopRequested = true;
}
Lock
Lock
• synchronized



 • lock() // synchronized

 • tryLock() //

 • tryLock(long,TimeUnit) //

 • lockInterruptibly() //
•

    •           try - finally
        Lock l = ...;
        l.lock();
        try {
            //
        } finally {
            l.unlock();
        }
ReentrantReadWriteLock rwLock = new ReentrantReadWriteLock();

Lock wl = rwLock.writeLock();
Lock rl;
wl.lock();
try {
    // write


    rl = rwLock.readLock();
} finally {
    wl.unlock();
}
try {
    // read
} finally {
    rl.unlock();
}
Lock
• lock()     synchronized



• unlock()     synchronized



•                Lock
java.util.concurrent
...

• wait()   notify()/notifyAll()
                                  (    )

•
java.util.concurrent
•
    Javadoc of java.util.concurrent
    • ExecutorService
    •

    •

    •

    • ConcurrentCollections
    •
• synchronized

• Java           17.4 Memory Model

•                       java.util.concurrent



•     Java

    • Doug Lea    ISBN:4-7973-3720-6

More Related Content

What's hot

Csw2016 gong pwn_a_nexus_device_with_a_single_vulnerability
Csw2016 gong pwn_a_nexus_device_with_a_single_vulnerabilityCsw2016 gong pwn_a_nexus_device_with_a_single_vulnerability
Csw2016 gong pwn_a_nexus_device_with_a_single_vulnerabilityCanSecWest
 
Full solution to bounded buffer
Full solution to bounded bufferFull solution to bounded buffer
Full solution to bounded bufferSyed Zaid Irshad
 
Grand Central Dispatch in Objective-C
Grand Central Dispatch in Objective-CGrand Central Dispatch in Objective-C
Grand Central Dispatch in Objective-CPavel Albitsky
 
soft-shake.ch - Java SE 7: The Fork/Join Framework and Project Coin
soft-shake.ch - Java SE 7: The Fork/Join Framework and Project Coinsoft-shake.ch - Java SE 7: The Fork/Join Framework and Project Coin
soft-shake.ch - Java SE 7: The Fork/Join Framework and Project Coinsoft-shake.ch
 
The Art of JVM Profiling
The Art of JVM ProfilingThe Art of JVM Profiling
The Art of JVM ProfilingAndrei Pangin
 
Counter Wars (JEEConf 2016)
Counter Wars (JEEConf 2016)Counter Wars (JEEConf 2016)
Counter Wars (JEEConf 2016)Alexey Fyodorov
 
Java 7 Launch Event at LyonJUG, Lyon France. Fork / Join framework and Projec...
Java 7 Launch Event at LyonJUG, Lyon France. Fork / Join framework and Projec...Java 7 Launch Event at LyonJUG, Lyon France. Fork / Join framework and Projec...
Java 7 Launch Event at LyonJUG, Lyon France. Fork / Join framework and Projec...julien.ponge
 
Java 5 concurrency
Java 5 concurrencyJava 5 concurrency
Java 5 concurrencypriyank09
 
Code generation for alternative languages
Code generation for alternative languagesCode generation for alternative languages
Code generation for alternative languagesRafael Winterhalter
 
Java 7 at SoftShake 2011
Java 7 at SoftShake 2011Java 7 at SoftShake 2011
Java 7 at SoftShake 2011julien.ponge
 
Java 7 JUG Summer Camp
Java 7 JUG Summer CampJava 7 JUG Summer Camp
Java 7 JUG Summer Campjulien.ponge
 
Csw2016 gawlik bypassing_differentdefenseschemes
Csw2016 gawlik bypassing_differentdefenseschemesCsw2016 gawlik bypassing_differentdefenseschemes
Csw2016 gawlik bypassing_differentdefenseschemesCanSecWest
 
Software Testing - Invited Lecture at UNSW Sydney
Software Testing - Invited Lecture at UNSW SydneySoftware Testing - Invited Lecture at UNSW Sydney
Software Testing - Invited Lecture at UNSW Sydneyjulien.ponge
 

What's hot (19)

Csw2016 gong pwn_a_nexus_device_with_a_single_vulnerability
Csw2016 gong pwn_a_nexus_device_with_a_single_vulnerabilityCsw2016 gong pwn_a_nexus_device_with_a_single_vulnerability
Csw2016 gong pwn_a_nexus_device_with_a_single_vulnerability
 
Migrating to JUnit 5
Migrating to JUnit 5Migrating to JUnit 5
Migrating to JUnit 5
 
Full solution to bounded buffer
Full solution to bounded bufferFull solution to bounded buffer
Full solution to bounded buffer
 
Java Concurrency
Java ConcurrencyJava Concurrency
Java Concurrency
 
Grand Central Dispatch in Objective-C
Grand Central Dispatch in Objective-CGrand Central Dispatch in Objective-C
Grand Central Dispatch in Objective-C
 
soft-shake.ch - Java SE 7: The Fork/Join Framework and Project Coin
soft-shake.ch - Java SE 7: The Fork/Join Framework and Project Coinsoft-shake.ch - Java SE 7: The Fork/Join Framework and Project Coin
soft-shake.ch - Java SE 7: The Fork/Join Framework and Project Coin
 
The Art of JVM Profiling
The Art of JVM ProfilingThe Art of JVM Profiling
The Art of JVM Profiling
 
Counter Wars (JEEConf 2016)
Counter Wars (JEEConf 2016)Counter Wars (JEEConf 2016)
Counter Wars (JEEConf 2016)
 
Java 7 Launch Event at LyonJUG, Lyon France. Fork / Join framework and Projec...
Java 7 Launch Event at LyonJUG, Lyon France. Fork / Join framework and Projec...Java 7 Launch Event at LyonJUG, Lyon France. Fork / Join framework and Projec...
Java 7 Launch Event at LyonJUG, Lyon France. Fork / Join framework and Projec...
 
Java 7 LavaJUG
Java 7 LavaJUGJava 7 LavaJUG
Java 7 LavaJUG
 
Java 5 concurrency
Java 5 concurrencyJava 5 concurrency
Java 5 concurrency
 
C++ Advanced Features
C++ Advanced FeaturesC++ Advanced Features
C++ Advanced Features
 
C++ Advanced Features
C++ Advanced FeaturesC++ Advanced Features
C++ Advanced Features
 
concurrency_c#_public
concurrency_c#_publicconcurrency_c#_public
concurrency_c#_public
 
Code generation for alternative languages
Code generation for alternative languagesCode generation for alternative languages
Code generation for alternative languages
 
Java 7 at SoftShake 2011
Java 7 at SoftShake 2011Java 7 at SoftShake 2011
Java 7 at SoftShake 2011
 
Java 7 JUG Summer Camp
Java 7 JUG Summer CampJava 7 JUG Summer Camp
Java 7 JUG Summer Camp
 
Csw2016 gawlik bypassing_differentdefenseschemes
Csw2016 gawlik bypassing_differentdefenseschemesCsw2016 gawlik bypassing_differentdefenseschemes
Csw2016 gawlik bypassing_differentdefenseschemes
 
Software Testing - Invited Lecture at UNSW Sydney
Software Testing - Invited Lecture at UNSW SydneySoftware Testing - Invited Lecture at UNSW Sydney
Software Testing - Invited Lecture at UNSW Sydney
 

Viewers also liked

Viewers also liked (6)

076-600.pdf
076-600.pdf076-600.pdf
076-600.pdf
 
Flisol Uni 2009
Flisol Uni 2009Flisol Uni 2009
Flisol Uni 2009
 
Successful Citizen Service - This Road's Built for You
Successful Citizen Service - This Road's Built for YouSuccessful Citizen Service - This Road's Built for You
Successful Citizen Service - This Road's Built for You
 
for Perl newbie
for Perl newbiefor Perl newbie
for Perl newbie
 
孩子你慢慢来
孩子你慢慢来孩子你慢慢来
孩子你慢慢来
 
Promoting best practice for early warning of landslides - Reclaim 3
Promoting best practice for early warning of landslides - Reclaim 3Promoting best practice for early warning of landslides - Reclaim 3
Promoting best practice for early warning of landslides - Reclaim 3
 

Similar to ぐだ生 Java入門第ニ回(synchronized and lock)

Java synchronizers
Java synchronizersJava synchronizers
Java synchronizersts_v_murthy
 
Non blocking io with netty
Non blocking io with nettyNon blocking io with netty
Non blocking io with nettyZauber
 
JavaOne 2012 - JVM JIT for Dummies
JavaOne 2012 - JVM JIT for DummiesJavaOne 2012 - JVM JIT for Dummies
JavaOne 2012 - JVM JIT for DummiesCharles Nutter
 
.NET Multithreading and File I/O
.NET Multithreading and File I/O.NET Multithreading and File I/O
.NET Multithreading and File I/OJussi Pohjolainen
 
Java concurrency begining
Java concurrency   beginingJava concurrency   begining
Java concurrency beginingmaksym220889
 
Concurrency in Programming Languages
Concurrency in Programming LanguagesConcurrency in Programming Languages
Concurrency in Programming LanguagesYudong Li
 
Java Concurrency Idioms
Java Concurrency IdiomsJava Concurrency Idioms
Java Concurrency IdiomsAlex Miller
 
CSharp for Unity Day2
CSharp for Unity Day2CSharp for Unity Day2
CSharp for Unity Day2Duong Thanh
 
Java Concurrency, Memory Model, and Trends
Java Concurrency, Memory Model, and TrendsJava Concurrency, Memory Model, and Trends
Java Concurrency, Memory Model, and TrendsCarol McDonald
 
Real-Time Streaming with Apache Spark Streaming and Apache Storm
Real-Time Streaming with Apache Spark Streaming and Apache StormReal-Time Streaming with Apache Spark Streaming and Apache Storm
Real-Time Streaming with Apache Spark Streaming and Apache StormDavorin Vukelic
 
Kotlin coroutine - the next step for RxJava developer?
Kotlin coroutine - the next step for RxJava developer?Kotlin coroutine - the next step for RxJava developer?
Kotlin coroutine - the next step for RxJava developer?Artur Latoszewski
 
Paradigma FP y OOP usando técnicas avanzadas de Programación | Programacion A...
Paradigma FP y OOP usando técnicas avanzadas de Programación | Programacion A...Paradigma FP y OOP usando técnicas avanzadas de Programación | Programacion A...
Paradigma FP y OOP usando técnicas avanzadas de Programación | Programacion A...Víctor Bolinches
 
Fork and join framework
Fork and join frameworkFork and join framework
Fork and join frameworkMinh Tran
 
Javaoneconcurrencygotchas 090610192215 Phpapp02
Javaoneconcurrencygotchas 090610192215 Phpapp02Javaoneconcurrencygotchas 090610192215 Phpapp02
Javaoneconcurrencygotchas 090610192215 Phpapp02Tarun Kumar
 

Similar to ぐだ生 Java入門第ニ回(synchronized and lock) (20)

Java synchronizers
Java synchronizersJava synchronizers
Java synchronizers
 
Non blocking io with netty
Non blocking io with nettyNon blocking io with netty
Non blocking io with netty
 
JavaOne 2012 - JVM JIT for Dummies
JavaOne 2012 - JVM JIT for DummiesJavaOne 2012 - JVM JIT for Dummies
JavaOne 2012 - JVM JIT for Dummies
 
.NET Multithreading and File I/O
.NET Multithreading and File I/O.NET Multithreading and File I/O
.NET Multithreading and File I/O
 
Concurrency gotchas
Concurrency gotchasConcurrency gotchas
Concurrency gotchas
 
Java concurrency begining
Java concurrency   beginingJava concurrency   begining
Java concurrency begining
 
Java concurrency
Java concurrencyJava concurrency
Java concurrency
 
Thread
ThreadThread
Thread
 
Concurrency in Programming Languages
Concurrency in Programming LanguagesConcurrency in Programming Languages
Concurrency in Programming Languages
 
Java Concurrency Idioms
Java Concurrency IdiomsJava Concurrency Idioms
Java Concurrency Idioms
 
CSharp for Unity Day2
CSharp for Unity Day2CSharp for Unity Day2
CSharp for Unity Day2
 
Java Concurrency, Memory Model, and Trends
Java Concurrency, Memory Model, and TrendsJava Concurrency, Memory Model, and Trends
Java Concurrency, Memory Model, and Trends
 
Real-Time Streaming with Apache Spark Streaming and Apache Storm
Real-Time Streaming with Apache Spark Streaming and Apache StormReal-Time Streaming with Apache Spark Streaming and Apache Storm
Real-Time Streaming with Apache Spark Streaming and Apache Storm
 
Kotlin coroutine - the next step for RxJava developer?
Kotlin coroutine - the next step for RxJava developer?Kotlin coroutine - the next step for RxJava developer?
Kotlin coroutine - the next step for RxJava developer?
 
Paradigma FP y OOP usando técnicas avanzadas de Programación | Programacion A...
Paradigma FP y OOP usando técnicas avanzadas de Programación | Programacion A...Paradigma FP y OOP usando técnicas avanzadas de Programación | Programacion A...
Paradigma FP y OOP usando técnicas avanzadas de Programación | Programacion A...
 
Multithreading in Java
Multithreading in JavaMultithreading in Java
Multithreading in Java
 
Chapter v(error)
Chapter v(error)Chapter v(error)
Chapter v(error)
 
Fork and join framework
Fork and join frameworkFork and join framework
Fork and join framework
 
Javaoneconcurrencygotchas 090610192215 Phpapp02
Javaoneconcurrencygotchas 090610192215 Phpapp02Javaoneconcurrencygotchas 090610192215 Phpapp02
Javaoneconcurrencygotchas 090610192215 Phpapp02
 
Play image
Play imagePlay image
Play image
 

More from Makoto Yamazaki

20150425 DroidKaigi つかえるGradleプロジェクトの作り方
20150425 DroidKaigi つかえるGradleプロジェクトの作り方20150425 DroidKaigi つかえるGradleプロジェクトの作り方
20150425 DroidKaigi つかえるGradleプロジェクトの作り方Makoto Yamazaki
 
Custom lintcheckをつくろう
Custom lintcheckをつくろうCustom lintcheckをつくろう
Custom lintcheckをつくろうMakoto Yamazaki
 
20120516 第7回ウフィカ社内ハンズオン Git基礎
20120516 第7回ウフィカ社内ハンズオン Git基礎20120516 第7回ウフィカ社内ハンズオン Git基礎
20120516 第7回ウフィカ社内ハンズオン Git基礎Makoto Yamazaki
 
ICS ホットトピック
ICS ホットトピックICS ホットトピック
ICS ホットトピックMakoto Yamazaki
 
DevQuiz 2011 の模範解答 Android編
DevQuiz 2011 の模範解答 Android編DevQuiz 2011 の模範解答 Android編
DevQuiz 2011 の模範解答 Android編Makoto Yamazaki
 
USB Host APIで遊んでみた
USB Host APIで遊んでみたUSB Host APIで遊んでみた
USB Host APIで遊んでみたMakoto Yamazaki
 
20110619 live view ideathon_logcatonliveview
20110619 live view ideathon_logcatonliveview20110619 live view ideathon_logcatonliveview
20110619 live view ideathon_logcatonliveviewMakoto Yamazaki
 
I/O 2011 報告会 ADKで遊んでみた
I/O 2011 報告会 ADKで遊んでみたI/O 2011 報告会 ADKで遊んでみた
I/O 2011 報告会 ADKで遊んでみたMakoto Yamazaki
 
ぐだ生 Java入門第三回(文字コードの話)(Keynote版)
ぐだ生 Java入門第三回(文字コードの話)(Keynote版)ぐだ生 Java入門第三回(文字コードの話)(Keynote版)
ぐだ生 Java入門第三回(文字コードの話)(Keynote版)Makoto Yamazaki
 
ぐだ生 Java入門第ニ回(synchronized and lock)
ぐだ生 Java入門第ニ回(synchronized and lock)ぐだ生 Java入門第ニ回(synchronized and lock)
ぐだ生 Java入門第ニ回(synchronized and lock)Makoto Yamazaki
 
ぐだ生 Java入門第一回(equals hash code_tostring)
ぐだ生 Java入門第一回(equals hash code_tostring)ぐだ生 Java入門第一回(equals hash code_tostring)
ぐだ生 Java入門第一回(equals hash code_tostring)Makoto Yamazaki
 
20110326 ネットプリントの紹介
20110326 ネットプリントの紹介20110326 ネットプリントの紹介
20110326 ネットプリントの紹介Makoto Yamazaki
 
20110109 abc2010w gingerbread_api_storage
20110109 abc2010w gingerbread_api_storage20110109 abc2010w gingerbread_api_storage
20110109 abc2010w gingerbread_api_storageMakoto Yamazaki
 

More from Makoto Yamazaki (13)

20150425 DroidKaigi つかえるGradleプロジェクトの作り方
20150425 DroidKaigi つかえるGradleプロジェクトの作り方20150425 DroidKaigi つかえるGradleプロジェクトの作り方
20150425 DroidKaigi つかえるGradleプロジェクトの作り方
 
Custom lintcheckをつくろう
Custom lintcheckをつくろうCustom lintcheckをつくろう
Custom lintcheckをつくろう
 
20120516 第7回ウフィカ社内ハンズオン Git基礎
20120516 第7回ウフィカ社内ハンズオン Git基礎20120516 第7回ウフィカ社内ハンズオン Git基礎
20120516 第7回ウフィカ社内ハンズオン Git基礎
 
ICS ホットトピック
ICS ホットトピックICS ホットトピック
ICS ホットトピック
 
DevQuiz 2011 の模範解答 Android編
DevQuiz 2011 の模範解答 Android編DevQuiz 2011 の模範解答 Android編
DevQuiz 2011 の模範解答 Android編
 
USB Host APIで遊んでみた
USB Host APIで遊んでみたUSB Host APIで遊んでみた
USB Host APIで遊んでみた
 
20110619 live view ideathon_logcatonliveview
20110619 live view ideathon_logcatonliveview20110619 live view ideathon_logcatonliveview
20110619 live view ideathon_logcatonliveview
 
I/O 2011 報告会 ADKで遊んでみた
I/O 2011 報告会 ADKで遊んでみたI/O 2011 報告会 ADKで遊んでみた
I/O 2011 報告会 ADKで遊んでみた
 
ぐだ生 Java入門第三回(文字コードの話)(Keynote版)
ぐだ生 Java入門第三回(文字コードの話)(Keynote版)ぐだ生 Java入門第三回(文字コードの話)(Keynote版)
ぐだ生 Java入門第三回(文字コードの話)(Keynote版)
 
ぐだ生 Java入門第ニ回(synchronized and lock)
ぐだ生 Java入門第ニ回(synchronized and lock)ぐだ生 Java入門第ニ回(synchronized and lock)
ぐだ生 Java入門第ニ回(synchronized and lock)
 
ぐだ生 Java入門第一回(equals hash code_tostring)
ぐだ生 Java入門第一回(equals hash code_tostring)ぐだ生 Java入門第一回(equals hash code_tostring)
ぐだ生 Java入門第一回(equals hash code_tostring)
 
20110326 ネットプリントの紹介
20110326 ネットプリントの紹介20110326 ネットプリントの紹介
20110326 ネットプリントの紹介
 
20110109 abc2010w gingerbread_api_storage
20110109 abc2010w gingerbread_api_storage20110109 abc2010w gingerbread_api_storage
20110109 abc2010w gingerbread_api_storage
 

Recently uploaded

A Journey Into the Emotions of Software Developers
A Journey Into the Emotions of Software DevelopersA Journey Into the Emotions of Software Developers
A Journey Into the Emotions of Software DevelopersNicole Novielli
 
The Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptx
The Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptxThe Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptx
The Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptxLoriGlavin3
 
Unleashing Real-time Insights with ClickHouse_ Navigating the Landscape in 20...
Unleashing Real-time Insights with ClickHouse_ Navigating the Landscape in 20...Unleashing Real-time Insights with ClickHouse_ Navigating the Landscape in 20...
Unleashing Real-time Insights with ClickHouse_ Navigating the Landscape in 20...Alkin Tezuysal
 
Data governance with Unity Catalog Presentation
Data governance with Unity Catalog PresentationData governance with Unity Catalog Presentation
Data governance with Unity Catalog PresentationKnoldus Inc.
 
2024 April Patch Tuesday
2024 April Patch Tuesday2024 April Patch Tuesday
2024 April Patch TuesdayIvanti
 
Connecting the Dots for Information Discovery.pdf
Connecting the Dots for Information Discovery.pdfConnecting the Dots for Information Discovery.pdf
Connecting the Dots for Information Discovery.pdfNeo4j
 
Modern Roaming for Notes and Nomad – Cheaper Faster Better Stronger
Modern Roaming for Notes and Nomad – Cheaper Faster Better StrongerModern Roaming for Notes and Nomad – Cheaper Faster Better Stronger
Modern Roaming for Notes and Nomad – Cheaper Faster Better Strongerpanagenda
 
Long journey of Ruby standard library at RubyConf AU 2024
Long journey of Ruby standard library at RubyConf AU 2024Long journey of Ruby standard library at RubyConf AU 2024
Long journey of Ruby standard library at RubyConf AU 2024Hiroshi SHIBATA
 
Take control of your SAP testing with UiPath Test Suite
Take control of your SAP testing with UiPath Test SuiteTake control of your SAP testing with UiPath Test Suite
Take control of your SAP testing with UiPath Test SuiteDianaGray10
 
Enhancing User Experience - Exploring the Latest Features of Tallyman Axis Lo...
Enhancing User Experience - Exploring the Latest Features of Tallyman Axis Lo...Enhancing User Experience - Exploring the Latest Features of Tallyman Axis Lo...
Enhancing User Experience - Exploring the Latest Features of Tallyman Axis Lo...Scott Andery
 
How AI, OpenAI, and ChatGPT impact business and software.
How AI, OpenAI, and ChatGPT impact business and software.How AI, OpenAI, and ChatGPT impact business and software.
How AI, OpenAI, and ChatGPT impact business and software.Curtis Poe
 
Passkey Providers and Enabling Portability: FIDO Paris Seminar.pptx
Passkey Providers and Enabling Portability: FIDO Paris Seminar.pptxPasskey Providers and Enabling Portability: FIDO Paris Seminar.pptx
Passkey Providers and Enabling Portability: FIDO Paris Seminar.pptxLoriGlavin3
 
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024BookNet Canada
 
Genislab builds better products and faster go-to-market with Lean project man...
Genislab builds better products and faster go-to-market with Lean project man...Genislab builds better products and faster go-to-market with Lean project man...
Genislab builds better products and faster go-to-market with Lean project man...Farhan Tariq
 
The Future Roadmap for the Composable Data Stack - Wes McKinney - Data Counci...
The Future Roadmap for the Composable Data Stack - Wes McKinney - Data Counci...The Future Roadmap for the Composable Data Stack - Wes McKinney - Data Counci...
The Future Roadmap for the Composable Data Stack - Wes McKinney - Data Counci...Wes McKinney
 
Why device, WIFI, and ISP insights are crucial to supporting remote Microsoft...
Why device, WIFI, and ISP insights are crucial to supporting remote Microsoft...Why device, WIFI, and ISP insights are crucial to supporting remote Microsoft...
Why device, WIFI, and ISP insights are crucial to supporting remote Microsoft...panagenda
 
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
 
From Family Reminiscence to Scholarly Archive .
From Family Reminiscence to Scholarly Archive .From Family Reminiscence to Scholarly Archive .
From Family Reminiscence to Scholarly Archive .Alan Dix
 
Assure Ecommerce and Retail Operations Uptime with ThousandEyes
Assure Ecommerce and Retail Operations Uptime with ThousandEyesAssure Ecommerce and Retail Operations Uptime with ThousandEyes
Assure Ecommerce and Retail Operations Uptime with ThousandEyesThousandEyes
 
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptx
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptxMerck Moving Beyond Passwords: FIDO Paris Seminar.pptx
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptxLoriGlavin3
 

Recently uploaded (20)

A Journey Into the Emotions of Software Developers
A Journey Into the Emotions of Software DevelopersA Journey Into the Emotions of Software Developers
A Journey Into the Emotions of Software Developers
 
The Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptx
The Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptxThe Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptx
The Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptx
 
Unleashing Real-time Insights with ClickHouse_ Navigating the Landscape in 20...
Unleashing Real-time Insights with ClickHouse_ Navigating the Landscape in 20...Unleashing Real-time Insights with ClickHouse_ Navigating the Landscape in 20...
Unleashing Real-time Insights with ClickHouse_ Navigating the Landscape in 20...
 
Data governance with Unity Catalog Presentation
Data governance with Unity Catalog PresentationData governance with Unity Catalog Presentation
Data governance with Unity Catalog Presentation
 
2024 April Patch Tuesday
2024 April Patch Tuesday2024 April Patch Tuesday
2024 April Patch Tuesday
 
Connecting the Dots for Information Discovery.pdf
Connecting the Dots for Information Discovery.pdfConnecting the Dots for Information Discovery.pdf
Connecting the Dots for Information Discovery.pdf
 
Modern Roaming for Notes and Nomad – Cheaper Faster Better Stronger
Modern Roaming for Notes and Nomad – Cheaper Faster Better StrongerModern Roaming for Notes and Nomad – Cheaper Faster Better Stronger
Modern Roaming for Notes and Nomad – Cheaper Faster Better Stronger
 
Long journey of Ruby standard library at RubyConf AU 2024
Long journey of Ruby standard library at RubyConf AU 2024Long journey of Ruby standard library at RubyConf AU 2024
Long journey of Ruby standard library at RubyConf AU 2024
 
Take control of your SAP testing with UiPath Test Suite
Take control of your SAP testing with UiPath Test SuiteTake control of your SAP testing with UiPath Test Suite
Take control of your SAP testing with UiPath Test Suite
 
Enhancing User Experience - Exploring the Latest Features of Tallyman Axis Lo...
Enhancing User Experience - Exploring the Latest Features of Tallyman Axis Lo...Enhancing User Experience - Exploring the Latest Features of Tallyman Axis Lo...
Enhancing User Experience - Exploring the Latest Features of Tallyman Axis Lo...
 
How AI, OpenAI, and ChatGPT impact business and software.
How AI, OpenAI, and ChatGPT impact business and software.How AI, OpenAI, and ChatGPT impact business and software.
How AI, OpenAI, and ChatGPT impact business and software.
 
Passkey Providers and Enabling Portability: FIDO Paris Seminar.pptx
Passkey Providers and Enabling Portability: FIDO Paris Seminar.pptxPasskey Providers and Enabling Portability: FIDO Paris Seminar.pptx
Passkey Providers and Enabling Portability: FIDO Paris Seminar.pptx
 
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
 
Genislab builds better products and faster go-to-market with Lean project man...
Genislab builds better products and faster go-to-market with Lean project man...Genislab builds better products and faster go-to-market with Lean project man...
Genislab builds better products and faster go-to-market with Lean project man...
 
The Future Roadmap for the Composable Data Stack - Wes McKinney - Data Counci...
The Future Roadmap for the Composable Data Stack - Wes McKinney - Data Counci...The Future Roadmap for the Composable Data Stack - Wes McKinney - Data Counci...
The Future Roadmap for the Composable Data Stack - Wes McKinney - Data Counci...
 
Why device, WIFI, and ISP insights are crucial to supporting remote Microsoft...
Why device, WIFI, and ISP insights are crucial to supporting remote Microsoft...Why device, WIFI, and ISP insights are crucial to supporting remote Microsoft...
Why device, WIFI, and ISP insights are crucial to supporting remote Microsoft...
 
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
 
From Family Reminiscence to Scholarly Archive .
From Family Reminiscence to Scholarly Archive .From Family Reminiscence to Scholarly Archive .
From Family Reminiscence to Scholarly Archive .
 
Assure Ecommerce and Retail Operations Uptime with ThousandEyes
Assure Ecommerce and Retail Operations Uptime with ThousandEyesAssure Ecommerce and Retail Operations Uptime with ThousandEyes
Assure Ecommerce and Retail Operations Uptime with ThousandEyes
 
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptx
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptxMerck Moving Beyond Passwords: FIDO Paris Seminar.pptx
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptx
 

ぐだ生 Java入門第ニ回(synchronized and lock)

  • 1. Java Thread 2011 4 9 twitter: @zaki50
  • 2. Who am I • YAMAZAKI Makoto(twitter: @zaki50) • Android • • StickyShortcut • Java
  • 3. • Effective Java 2 • ISBN:978-4-89471-499-1 • 3,780 ( ) • 66, 69
  • 4. Agenda • synchronized / volatile • Lock(ReentrantLock) • java.util.concurrent
  • 6. Eclipse (jvisualvm)
  • 7. synchronized class Sample { public synchronized void execute1() { // } public void execute1b() { synchronized (this) { // } } public static synchronized void execute2() { // } public static synchronized void execute2b() { synchronized (Sample.class) { // } } }
  • 9.
  • 10.
  • 11. (by Wikipedia) • Java 1 1 1 1
  • 12. • synchronized • Object#wait() • • synchronized • Object#wait()
  • 13. synchronized •
  • 14. synchronized class Sample { public synchronized void execute1() { // } public void execute1b() { synchronized (this) { // } } public static synchronized void execute2() { // } public static synchronized void execute2b() { synchronized (Sample.class) { // } } }
  • 15.
  • 16.
  • 17. • Java VM • • •
  • 18. private static boolean stopRequested = false; private static int value = 0; public static void main(String[] args) throws Exception { new Thread() { @Override public void run() { int i = 0; if (!stopRequested) { while (!stopRequested) { while (true) { i++; i++; } } } System.out.println(value); } }.start(); TimeUnit.SECONDS.sleep(1L); value = 100; stopRequested = true; }
  • 19. private static boolean stopRequested = false; private static int value = 0; public static void main(String[] args) throws Exception { new Thread() { @Override public void run() { int i = 0; while (!stopped()) { i++; } System.out.println(value); } }.start(); private synchronized static void stop() { stopRequested = true; TimeUnit.SECONDS.sleep(1L); } value = 100; stop(); private synchronized static boolean stopped() { } return stopRequested; }
  • 22. volatile private volatile static boolean stopRequested = false; private volatile static int value = 0; public static void main(String[] args) throws Exception { new Thread() { @Override public void run() { int i = 0; while (!stopRequested) { i++; } System.out.println(value); } }.start(); TimeUnit.SECONDS.sleep(1L); value = 100; stopRequested = true; }
  • 23. Lock
  • 24. Lock • synchronized • lock() // synchronized • tryLock() // • tryLock(long,TimeUnit) // • lockInterruptibly() //
  • 25. • try - finally Lock l = ...; l.lock(); try { // } finally { l.unlock(); }
  • 26. ReentrantReadWriteLock rwLock = new ReentrantReadWriteLock(); Lock wl = rwLock.writeLock(); Lock rl; wl.lock(); try { // write rl = rwLock.readLock(); } finally { wl.unlock(); } try { // read } finally { rl.unlock(); }
  • 27. Lock • lock() synchronized • unlock() synchronized • Lock
  • 29. ... • wait() notify()/notifyAll() ( ) •
  • 30. java.util.concurrent • Javadoc of java.util.concurrent • ExecutorService • • • • ConcurrentCollections •
  • 31. • synchronized • Java 17.4 Memory Model • java.util.concurrent • Java • Doug Lea ISBN:4-7973-3720-6

Editor's Notes

  1. \n
  2. \n
  3. \n
  4. \n
  5. \n
  6. \n
  7. \n
  8. \n
  9. \n
  10. \n
  11. \n
  12. \n
  13. \n
  14. \n
  15. \n
  16. \n
  17. \n
  18. \n
  19. \n
  20. \n
  21. \n
  22. \n
  23. \n
  24. \n
  25. \n
  26. \n
  27. \n
  28. \n
  29. \n
  30. \n
  31. \n