Training Sesi #6
Java Concurrency



Petra Novandi Barus
petra.barus@gmail.com
Summary
 Concurrency
 Process and Thread
 Thread
 Sleep/Interrupt/Join
 Synchronization
 Timer



                        2
Concurrency
 Aktivitas yang dilakukan secara bersamaan
 Sebuah komputer menjalankan
 ◦ Word processor
 ◦ Music Player
 ◦ Web browser
 Sebuah music player menjalankan
 ◦ Pemutaran lagu
 ◦ Pemilihan lagu
 ◦ Visualisasi lagu
                                         3
Process and Thread
 Process
 ◦ Private resource
 Thread
 ◦ Berjalan di dalam process
 ◦ Resource sharing milik process




                                    4
Process and Thread (2)
 Mekanisme tergantung dari sistem operasi
 dan prosesor
 Pelatihan ini fokus pada Thread




                                        5
Thread
 Pembuatan thread dapat dilakukan dgn 2 cara
 ◦ Extend class java.lang.Thread
 ◦ Implement interface java.lang.Runnable
 Extend Thread
 ◦ Digunakan jika thread sederhana, tidak ada fungsi
   tambahan
 Implement Runnable
 ◦ Digunakan pada sebuah thread yang mengextend
   kelas selain Thread
 ◦ Berguna untuk kelas yg memiliki banyak fungsi
                                                       6
public class Thread1 extends Thread{
  @Override
  public void run() {
      for (int i = 0; i <= 100; i++) {

System.out.println(String.format("%d", i));
     }
  }
}




                                              7
public class Main {
  public static void main(String argv[]) {
      Thread1 thread1 = new Thread1();
      thread1.start();
  }
}




                                             8
public static void main(String argv[]) {
  Thread1 thread1 = new Thread1();
  Thread1 thread2 = new Thread1();
  Thread1 thread3 = new Thread1();
  thread1.start();
  thread2.start();
  thread3.start();
}




                                           9
thread1   thread2   thread3   output
1                             1
2                             2
                    1         1
                    2         2
          1                   1
3                             3
          2                   2
          3                   3
                    3         3
          4                   4
                    4         4
          5                   5
4                             4
                    5         5
..        ..        ..        ..

                                       10
Demo




       11
Sleep, Interrupt, Join
 Sleep
 ◦ Mekanisme untuk mensuspend aktivitas
   sebuah Thread
 ◦ Invokasi method sleep
 ◦ Input millisecond, lama waktu sleep
 ◦ Tidak ada jaminan waktu tepat
 Interrupt
 Join


                                          12
public class Thread1 extends Thread {
  @Override
  public void run() {
      for (int i = 0; i <= 100; i++) {
         System.out.println(String.format("%d", i));
         try {
             Thread.sleep(100);
         } catch (InterruptedException ex) {

Logger.getLogger(Thread1.class.getName()).log(Level.SEVERE
, null, ex);
          }
       }
   }
}




                                                         13
Sleep, Interrupt, Join (2)
 Sleep
 Interrupt
 ◦ Mekanisme untuk menginterupsi jalannya
   Thread
 ◦ Menyuruh thread mengerjakan hal lain
 ◦ Invokasi method interrupt()
 ◦ Pada thread, menjalankan fungsi yg melempar
   InterruptedException
 ◦ Atau memeriksa hasil interrupted()
 Join
                                                 14
public static void main(String argv[]) {
      Thread2 thread2 = new Thread2();
      thread2.start();
      try {
         Thread.sleep(10);
         thread2.interrupt();
      } catch (InterruptedException ex) {

      }
  }




                                            15
Sleep, Interrupt, Join (3)
 Sleep
 Interrupt
 Join
 ◦ Menunggu sebuah thread selesai bekerja




                                            16
public static void main(String argv[]) {
  Thread1 thread1 = new Thread1();
  thread1.start();
  for (int i = 0; i <= 1000; i++) {
      System.out.println(String.format("%d", i));
      if (i == 30){
          try {
             System.out.println("Joining");
             thread1.join();
          } catch (InterruptedException ex) {
          }
      }
  }
}




                                                    17
Synchronization
 Thread berkomunikasi dengan
 menggunakan shared resource
 Dapat terjadi beberapa kesalahan
 ◦ Thread interference
 ◦ Memory consistency error
 Contoh kegagalan dapat dilihat pada
 modul
 Dibutuhkan penanganan sinkronisasi

                                       18
Thread1          value Thread2            value i
Retrieve i       0                                   0
                       Retrieve i         0          0
Increment value 1                                    0
                       Decrement value    -1         0
Store value to i 1                                   1
                       Store value to i   -1        -1




                                                         19
Thread1            value Thread2            value i
Retrieve i         0                                  0
Increment value    1                                  0
Store value to i   1                                  1
                         Retrieve i         1         1
                         Decrement value    0         1
                         Store value to i   0         0




                                                          20
Synchronization
 Synchronized Method
 ◦ Blok method lain yang ingin menggunakan
   resource yang sedang digunakan
 Synchronized Statement
 ◦ Locking sebuah obyek
 ◦ Faster
 ◦ More complex




                                             21
public class Hitung {
  public int i = 0;
  public synchronized void tambah() {
      i++;
  }
  public synchronized void kurang() {
      i--;
  }
}




                                        22
public class Hitung {
  public int i = 0;
  private final Object o = new Object();
  public void tambah() {
      synchronized (o) {
         i++;
      }
  }
  public void kurang() {
      synchronized (o) {
         i--;
      }
  }
}
                                           23
Timer
 Pengeksekusian sebuah task secara
 terjadwal atau periodik
 Menggunakan Timer dan TimerTask
 TimerTask mengimplementasikan task
 Timer menjadwalkan TimerTask




                                      24
public class ContohTask extends TimerTask {
  @Override
  public void run() {
      for (int i = 0; i <= 100; i++) {
         System.out.println(String.format("%d", i));
      }
  }
}

public class Main {
  public static void main(String argv[]) {
      Timer t = new Timer();
      t.schedule(new ContohTask(), 1000);
  }
}




                                                       25
Timer (2)
 Methods
 ◦ schedule(TimerTask task, Date date)
 ◦ schedule(TimerTask task, Date firstTime, long
   period)
 ◦ schedule(TimerTask task, long delay)
 ◦ schedule(TimerTask task, long delay), long period)




                                                        26
What Else?
 Problems
 ◦ Deadlock
 ◦ Starvation
 Java-related
 ◦ High level concurrency
 ◦ Concurrent collection
 ◦ java.util.concurrent
 Concurrency
 ◦ Process
 ◦ Multiprocessor (cluster, etc)
 ◦ Parallel programming

                                   27
Question?




            28

Slide sesi 6 - java concurrency

  • 1.
    Training Sesi #6 JavaConcurrency Petra Novandi Barus petra.barus@gmail.com
  • 2.
    Summary Concurrency Processand Thread Thread Sleep/Interrupt/Join Synchronization Timer 2
  • 3.
    Concurrency Aktivitas yangdilakukan secara bersamaan Sebuah komputer menjalankan ◦ Word processor ◦ Music Player ◦ Web browser Sebuah music player menjalankan ◦ Pemutaran lagu ◦ Pemilihan lagu ◦ Visualisasi lagu 3
  • 4.
    Process and Thread Process ◦ Private resource Thread ◦ Berjalan di dalam process ◦ Resource sharing milik process 4
  • 5.
    Process and Thread(2) Mekanisme tergantung dari sistem operasi dan prosesor Pelatihan ini fokus pada Thread 5
  • 6.
    Thread Pembuatan threaddapat dilakukan dgn 2 cara ◦ Extend class java.lang.Thread ◦ Implement interface java.lang.Runnable Extend Thread ◦ Digunakan jika thread sederhana, tidak ada fungsi tambahan Implement Runnable ◦ Digunakan pada sebuah thread yang mengextend kelas selain Thread ◦ Berguna untuk kelas yg memiliki banyak fungsi 6
  • 7.
    public class Thread1extends Thread{ @Override public void run() { for (int i = 0; i <= 100; i++) { System.out.println(String.format("%d", i)); } } } 7
  • 8.
    public class Main{ public static void main(String argv[]) { Thread1 thread1 = new Thread1(); thread1.start(); } } 8
  • 9.
    public static voidmain(String argv[]) { Thread1 thread1 = new Thread1(); Thread1 thread2 = new Thread1(); Thread1 thread3 = new Thread1(); thread1.start(); thread2.start(); thread3.start(); } 9
  • 10.
    thread1 thread2 thread3 output 1 1 2 2 1 1 2 2 1 1 3 3 2 2 3 3 3 3 4 4 4 4 5 5 4 4 5 5 .. .. .. .. 10
  • 11.
  • 12.
    Sleep, Interrupt, Join Sleep ◦ Mekanisme untuk mensuspend aktivitas sebuah Thread ◦ Invokasi method sleep ◦ Input millisecond, lama waktu sleep ◦ Tidak ada jaminan waktu tepat Interrupt Join 12
  • 13.
    public class Thread1extends Thread { @Override public void run() { for (int i = 0; i <= 100; i++) { System.out.println(String.format("%d", i)); try { Thread.sleep(100); } catch (InterruptedException ex) { Logger.getLogger(Thread1.class.getName()).log(Level.SEVERE , null, ex); } } } } 13
  • 14.
    Sleep, Interrupt, Join(2) Sleep Interrupt ◦ Mekanisme untuk menginterupsi jalannya Thread ◦ Menyuruh thread mengerjakan hal lain ◦ Invokasi method interrupt() ◦ Pada thread, menjalankan fungsi yg melempar InterruptedException ◦ Atau memeriksa hasil interrupted() Join 14
  • 15.
    public static voidmain(String argv[]) { Thread2 thread2 = new Thread2(); thread2.start(); try { Thread.sleep(10); thread2.interrupt(); } catch (InterruptedException ex) { } } 15
  • 16.
    Sleep, Interrupt, Join(3) Sleep Interrupt Join ◦ Menunggu sebuah thread selesai bekerja 16
  • 17.
    public static voidmain(String argv[]) { Thread1 thread1 = new Thread1(); thread1.start(); for (int i = 0; i <= 1000; i++) { System.out.println(String.format("%d", i)); if (i == 30){ try { System.out.println("Joining"); thread1.join(); } catch (InterruptedException ex) { } } } } 17
  • 18.
    Synchronization Thread berkomunikasidengan menggunakan shared resource Dapat terjadi beberapa kesalahan ◦ Thread interference ◦ Memory consistency error Contoh kegagalan dapat dilihat pada modul Dibutuhkan penanganan sinkronisasi 18
  • 19.
    Thread1 value Thread2 value i Retrieve i 0 0 Retrieve i 0 0 Increment value 1 0 Decrement value -1 0 Store value to i 1 1 Store value to i -1 -1 19
  • 20.
    Thread1 value Thread2 value i Retrieve i 0 0 Increment value 1 0 Store value to i 1 1 Retrieve i 1 1 Decrement value 0 1 Store value to i 0 0 20
  • 21.
    Synchronization Synchronized Method ◦ Blok method lain yang ingin menggunakan resource yang sedang digunakan Synchronized Statement ◦ Locking sebuah obyek ◦ Faster ◦ More complex 21
  • 22.
    public class Hitung{ public int i = 0; public synchronized void tambah() { i++; } public synchronized void kurang() { i--; } } 22
  • 23.
    public class Hitung{ public int i = 0; private final Object o = new Object(); public void tambah() { synchronized (o) { i++; } } public void kurang() { synchronized (o) { i--; } } } 23
  • 24.
    Timer Pengeksekusian sebuahtask secara terjadwal atau periodik Menggunakan Timer dan TimerTask TimerTask mengimplementasikan task Timer menjadwalkan TimerTask 24
  • 25.
    public class ContohTaskextends TimerTask { @Override public void run() { for (int i = 0; i <= 100; i++) { System.out.println(String.format("%d", i)); } } } public class Main { public static void main(String argv[]) { Timer t = new Timer(); t.schedule(new ContohTask(), 1000); } } 25
  • 26.
    Timer (2) Methods ◦ schedule(TimerTask task, Date date) ◦ schedule(TimerTask task, Date firstTime, long period) ◦ schedule(TimerTask task, long delay) ◦ schedule(TimerTask task, long delay), long period) 26
  • 27.
    What Else? Problems ◦ Deadlock ◦ Starvation Java-related ◦ High level concurrency ◦ Concurrent collection ◦ java.util.concurrent Concurrency ◦ Process ◦ Multiprocessor (cluster, etc) ◦ Parallel programming 27
  • 28.