download

Matakuliah
Tahun
Versi
: M0074/PROGRAMMING II
: 2005
: 1/0
MATERI PENDUKUNG
SINKRONISASI
1
• 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.
2
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.
3
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).
4
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.
5