Presentation is loading. Please wait.

Presentation is loading. Please wait.

1 MATERI PENDUKUNG SINKRONISASI Matakuliah: M0074/PROGRAMMING II Tahun: 2005 Versi: 1/0.

Similar presentations


Presentation on theme: "1 MATERI PENDUKUNG SINKRONISASI Matakuliah: M0074/PROGRAMMING II Tahun: 2005 Versi: 1/0."— Presentation transcript:

1 1 MATERI PENDUKUNG SINKRONISASI Matakuliah: M0074/PROGRAMMING II Tahun: 2005 Versi: 1/0

2 2 Synchronizing threads One of the central problems of multithreaded computing is handling situations where more than one thread has access to the same data structure. For example, if one thread was trying to update the elements in a list, while another thread was simultaneously trying to sort them, your program could deadlock or produce incorrect results.

3 3 To prevent this problem, you need to use thread synchronization. The simplest way to prevent two objects from accessing the same method at the same time is to require a thread to obtain a lock. While a thread holds the lock, another thread that needs a lock has to wait until the first thread releases the lock. To keep a method thread-safe, use the synchronized keyword when declaring methods that can only be executed by one thread at a time. Note than you can also synchronize on an object.

4 4 For example, if you create a swap() method that swaps values using a local variable and you create two different threads to execute the method, your program could produce incorrect results. The first thread, due to the Java scheduler, might only be able to execute the first half of the method. Then, the second thread might be able to execute the entire method, but using incorrect values (since the first thread did not complete the operation).

5 5 The first thread would then return to finish the method. In this case, it would appear as if the swapping of values never took place. To prevent this from happening, use the synchronized keyword in your method declaration. As a basic rule, any method that modifies an object's property should be declared synchronized.


Download ppt "1 MATERI PENDUKUNG SINKRONISASI Matakuliah: M0074/PROGRAMMING II Tahun: 2005 Versi: 1/0."

Similar presentations


Ads by Google