Java concurrency package: Difference between revisions

From Citizendium
Jump to navigation Jump to search
imported>Prn Dan Mo
imported>Prn Dan Mo
(Undo revision 100701896 by Prn Dan Mo (Talk))
Line 1: Line 1:
{{CZ:Special Topics 2010/EZnotice}}
{{subpages}}
{{TOC|right}}
The '''Java concurrency package''' is a library supporting threading and parallel programming in the Java programming language.
===Synchronizers===
====Mutilthread Synchronization before Java 5====
Before Java 5, multithreads are supported using the lock mechanism for synchronization. 
Locks are implemented in Synchronized method.  This mechanism “ensures that only one Java
thread can execute an object's synchronized methods at a time” and “also allows threads
to wait for resources to become available, and allows the thread that makes resources
available to notify other threads that are waiting for the resources”.
<ref name="Java Synchronization">
{{cite web|
url= http://www.d.umn.edu/~gshute/java/synchronization.html|
title=Java Synchronization|
accessdate=2010-08-12 |
author=Gary Shute| }}
</ref>.  When the
synchronized keyword is used, the thread which invokes the synchronized method must obtain
a lock for the object which makes this thread the lock holder. The rule of thumb of
synchronized method is that only one thread can hold this lock at a time.
Three most commonly used methods including, '''wait()''', '''notify()''', and '''notifyAll()''' are used for
resource communication between threads.
“The wait() method can only be invoked by the object's lock holder. It causes current thread
to wait until another thread invokes the notify() method or the notifyAll() method for this
object”
<ref name="J2SE API v1.4.2">
{{cite web|
url= http://download.oracle.com/javase/1.4.2/docs/api/java/lang/Object.html|
title=J2SE API v1.4.2|
accessdate=2010-08-12 |}}
</ref>.
The notify() method wakes up one thread and only the notified thread can go ahead and do
something. If there are more than one thread waiting on this object’s waiting queue, one
of them is selected to be woke up.  notify() wakes up the first thread in the waiting queue.
The notifyAll() method wakes up all threads in the wait set. notifyAll() is normally used
when there are many threads to wake up simultaneously.  Which thread gets the right to go
ahead to execute depends upon thread property such as their priority.
One of the biggest issues of synchronized method is that it is an “all-or-nothing thing”
<ref name="Problems with Java 1.4 synchronization model">
{{cite web|
url= http://www.javamex.com/tutorials/synchronization_concurrency_5.shtml|
title=Problems with Java 1.4 synchronization model|
accessdate=2010-08-12 |
author=Unknown| }}
</ref>.
“Once a thread attempts to enter a synchronized block, it will hang until the lock is available.”
<ref name="Problems with Java 1.4 synchronization model">
{{cite web|
url= http://www.javamex.com/tutorials/synchronization_concurrency_5.shtml|
title=Problems with Java 1.4 synchronization model|
accessdate=2010-08-12 |
author=Unknown| }}
</ref> which causes low performance because all other threads that need the same object have to wait.
Another issue is that missing appropriate notifications such as notify() or notifyAll() while
programming probably results in deadlock. <ref name="A Critique of Java for Concurrent Programming">
{{cite journal
  | last = V.K.
  | first = Garg
  | last2 = Mittal
  | first2 = Neeraj
  | title = A Critique of Java for Concurrent Programming
  | journal = IEEE Computer Society
  | volume = 6
  | issue = 9
  | date = September 2005
  | url = http://ieeexplore.ieee.org/stamp/stamp.jsp?tp=&arnumber=1524870
  | doi =
  | id =
  | accessdate = 2010-08-12}}
</ref>
====Java 5: Synchronizers====
In Java 5, the Java concurrent package provides four new classes including: '''semaphore''',
'''countdownlatch''', '''cyclickbarrier''', and '''exchanger''', used for data synchronization
<ref name="J2SE API v5.0">
{{cite web|
url= http://download.oracle.com/javase/1.5.0/docs/api/java/util/concurrent/package-summary.html|
title=J2SE API v5.0|
accessdate=2010-08-12 |}}
</ref>.
''Semaphore'' is a counting signal. It maintains a set of permits.  The “parking garage” can be
a good analogy as an example to explain it.  We can think of that the permits in semaphore
equals to the capability in a garage.  If the permits that have been issued reach the maximum
garage capacity, the garage is full.  No parking permit can be issued. The garage will have
some space for other cars when some permits are returned.
“''CountDownLatch'' is a synchronization aid that allows one or more threads to wait until a set
of operations being performed in other threads completes. It is initialized with a given count”
<ref name="public class: CountDownLatch">
{{cite web|
url= http://www.docjar.com/docs/api/java/util/concurrent/CountDownLatch.html|
title=public class: CountDownLatch|
accessdate=2010-08-12 |}}
</ref>.  Something here that needs to be mentioned that “CountDownLatch is a one-shot phenomenon”
<ref name="public class: CountDownLatch">
{{cite web|
url= http://www.docjar.com/docs/api/java/util/concurrent/CountDownLatch.html|
title=public class: CountDownLatch|
accessdate=2010-08-12 |}}
</ref> meaning that the counter cannot be reused. If you need a counter that can be reset, consider
using the CyclicBarrier method stating below.
''CyclicBarriers'' is an aid “which allows a set of threads to wait for each other to reach a
common barrier point” <ref name="public class: CountDownLatch">
{{cite web|
url= http://www.docjar.com/docs/api/java/util/concurrent/CountDownLatch.html|
title=public class: CountDownLatch|
accessdate=2010-08-12 |}}
</ref>.  CyclicBarriers is useful when a fixed sized group of thread is
occasionally but must wait for each other in a program.  “The barrier is called cyclic because
it can be re-used after the waiting threads are released” <ref name="public class: CountDownLatch">
{{cite web|
url= http://www.docjar.com/docs/api/java/util/concurrent/CountDownLatch.html|
title=public class: CountDownLatch|
accessdate=2010-08-12 |}}
</ref>.
''Exchanger'' is actually what the word looks like.  “It is a synchronization point where two
threads can exchange objects. Each thread presents some object on entry to the exchange method
and receives the object presented by the other thread on return” <ref name="public class: CountDownLatch">
{{cite web|
url= http://www.docjar.com/docs/api/java/util/concurrent/CountDownLatch.html|
title=public class: CountDownLatch|
accessdate=2010-08-12 |}}
</ref>.
===Concurrent Collections===
As it is mentioned in the beginning of synchronizer, the lock mechanism is implemented in
“synchronized” classes before Java 5 and “synchronized” method will lock the object that’s been
accessed by a thread.  When an object is locked by one thread, other threads which need to
access the same object are going to wait until the object is available.  Also, only the resources
in the object are protected.  Other resources outside the object are not.
"Synchronized classes can be useful when you need to prevent all access to a collection through
a single lock, at the expense of poorer scalability”<ref name="J2SE API v5.0">
{{cite web|
url= http://download.oracle.com/javase/1.5.0/docs/api/java/util/concurrent/package-summary.html|
title=J2SE API v5.0|
accessdate=2010-08-12 |}}
</ref>.
Java realized this issue and therefore enhanced it by supplying some more collection implementations
such as ConcurrentHashMap, CopyOnWriteArrayList , and CopyOnWriteArraySet.  Here only basic concepts
will be introduced here due to that this component is a very advanced one in java concurrent package. 
For more information, please refer to J2SE 5.0 official website [http://download.oracle.com/javase/1.5.0/docs/api/java/util/concurrent/package-summary.html Package java.util.concurrenct].
''ConcurrentHashMap:''
“It synchronizes different segments in a hash table, not the whole object. Therefore, other
threads can still access other segments that are not in synchronization”
<ref name="Concurrent Programming with J2SE 5.0">
{{cite web|
url= http://java.sun.com/developer/technicalArticles/J2SE/concurrency/|
title=Concurrent Programming with J2SE 5.0|
accessdate=2010-08-12 |
author=Qusay H. Mahmoud| }}
</ref>.  So other threads don’t have to wait.  This provides the thread safety and also improves balances of the
performance.
''CopyOnWriteArrayList:''
“It uses a reference to the state of the array at the point that the iterator was created. This
array never changes during the lifetime of the iterator, so interference is impossible”
<ref name="Concurrent Programming with J2SE 5.0">
{{cite web|
url= http://java.sun.com/developer/technicalArticles/J2SE/concurrency/|
title=Concurrent Programming with J2SE 5.0|
accessdate=2010-08-12 |
author=Qusay H. Mahmoud| }}
</ref>.  This means no modification will be allowed when using CopyOnWriteArrayList. Therefore this
operation is immutable and also guarantees thread-safety.
''CopyOnWriteArraySet:''
It’s a data structure to protect the data during traversal for modification of the Array.
With CopyOnWriteArraySet, any changes in the data structure during traversal results in a copy
being made for the modification.  However, there is something we have to keep in mind.  This
is used assuming in that there won’t be too many changes being made. If a lot of possible
modifications need to be performed, we are talking a lot of copies as well which could be bad.
{{CZ:Special Topics 2010/EZnotice}}
{{CZ:Special Topics 2010/EZnotice}}
{{subpages}}
{{subpages}}

Revision as of 13:58, 12 August 2010

All unapproved Citizendium articles may contain errors of fact, bias, grammar etc. A version of an article is unapproved unless it is marked as citable with a dedicated green template at the top of the page, as in this version of the 'Biology' article. Citable articles are intended to be of reasonably high quality. The participants in the Citizendium project make no representations about the reliability of Citizendium articles or, generally, their suitability for any purpose.

Nuvola apps kbounce green.png
Nuvola apps kbounce green.png
This article is currently being developed as part of an Eduzendium student project. The course homepage can be found at CZ:Special_Topics_2010.
To provide students with experience in collaboration, you are warmly invited to join in here, or to leave comments on the discussion page. The anticipated date of course completion is 13 August 2010. One month after that date at the latest, this notice shall be removed.
Besides, many other Citizendium articles welcome your collaboration!


This article is developing and not approved.
Main Article
Discussion
Related Articles  [?]
Bibliography  [?]
External Links  [?]
Citable Version  [?]
 
This editable Main Article is under development and subject to a disclaimer.


The Java concurrency package is a library supporting threading and parallel programming in the Java programming language.

Synchronizers

Mutilthread Synchronization before Java 5

Before Java 5, multithreads are supported using the lock mechanism for synchronization. Locks are implemented in Synchronized method. This mechanism “ensures that only one Java thread can execute an object's synchronized methods at a time” and “also allows threads to wait for resources to become available, and allows the thread that makes resources available to notify other threads that are waiting for the resources”. [1]. When the synchronized keyword is used, the thread which invokes the synchronized method must obtain a lock for the object which makes this thread the lock holder. The rule of thumb of synchronized method is that only one thread can hold this lock at a time.

Three most commonly used methods including, wait(), notify(), and notifyAll() are used for resource communication between threads.

“The wait() method can only be invoked by the object's lock holder. It causes current thread to wait until another thread invokes the notify() method or the notifyAll() method for this object” [2].

The notify() method wakes up one thread and only the notified thread can go ahead and do something. If there are more than one thread waiting on this object’s waiting queue, one of them is selected to be woke up. notify() wakes up the first thread in the waiting queue.

The notifyAll() method wakes up all threads in the wait set. notifyAll() is normally used when there are many threads to wake up simultaneously. Which thread gets the right to go ahead to execute depends upon thread property such as their priority.

One of the biggest issues of synchronized method is that it is an “all-or-nothing thing” [3]. “Once a thread attempts to enter a synchronized block, it will hang until the lock is available.” [3] which causes low performance because all other threads that need the same object have to wait. Another issue is that missing appropriate notifications such as notify() or notifyAll() while programming probably results in deadlock. [4]

Java 5: Synchronizers

In Java 5, the Java concurrent package provides four new classes including: semaphore, countdownlatch, cyclickbarrier, and exchanger, used for data synchronization [5].

Semaphore is a counting signal. It maintains a set of permits. The “parking garage” can be a good analogy as an example to explain it. We can think of that the permits in semaphore equals to the capability in a garage. If the permits that have been issued reach the maximum garage capacity, the garage is full. No parking permit can be issued. The garage will have some space for other cars when some permits are returned.

CountDownLatch is a synchronization aid that allows one or more threads to wait until a set of operations being performed in other threads completes. It is initialized with a given count” [6]. Something here that needs to be mentioned that “CountDownLatch is a one-shot phenomenon” [6] meaning that the counter cannot be reused. If you need a counter that can be reset, consider using the CyclicBarrier method stating below.

CyclicBarriers is an aid “which allows a set of threads to wait for each other to reach a common barrier point” [6]. CyclicBarriers is useful when a fixed sized group of thread is occasionally but must wait for each other in a program. “The barrier is called cyclic because it can be re-used after the waiting threads are released” [6].

Exchanger is actually what the word looks like. “It is a synchronization point where two threads can exchange objects. Each thread presents some object on entry to the exchange method and receives the object presented by the other thread on return” [6].

Concurrent Collections

As it is mentioned in the beginning of synchronizer, the lock mechanism is implemented in “synchronized” classes before Java 5 and “synchronized” method will lock the object that’s been accessed by a thread. When an object is locked by one thread, other threads which need to access the same object are going to wait until the object is available. Also, only the resources in the object are protected. Other resources outside the object are not.

"Synchronized classes can be useful when you need to prevent all access to a collection through a single lock, at the expense of poorer scalability”[5].

Java realized this issue and therefore enhanced it by supplying some more collection implementations such as ConcurrentHashMap, CopyOnWriteArrayList , and CopyOnWriteArraySet. Here only basic concepts will be introduced here due to that this component is a very advanced one in java concurrent package. For more information, please refer to J2SE 5.0 official website Package java.util.concurrenct.

ConcurrentHashMap: “It synchronizes different segments in a hash table, not the whole object. Therefore, other threads can still access other segments that are not in synchronization” [7]. So other threads don’t have to wait. This provides the thread safety and also improves balances of the performance.

CopyOnWriteArrayList: “It uses a reference to the state of the array at the point that the iterator was created. This array never changes during the lifetime of the iterator, so interference is impossible” [7]. This means no modification will be allowed when using CopyOnWriteArrayList. Therefore this operation is immutable and also guarantees thread-safety.

CopyOnWriteArraySet: It’s a data structure to protect the data during traversal for modification of the Array. With CopyOnWriteArraySet, any changes in the data structure during traversal results in a copy being made for the modification. However, there is something we have to keep in mind. This is used assuming in that there won’t be too many changes being made. If a lot of possible modifications need to be performed, we are talking a lot of copies as well which could be bad.

Conclusion

Capability

Java 5 still supports the standard concurrent unities which are contained in the previous version and has introduced the new java.util.concurrent package to make our life of concurrent development in Java easier by providing those high-quality implementations for the data synchronization mechanisms <ref name="Concurrent Programming with J2SE 5.0"> Qusay H. Mahmoud. Concurrent Programming with J2SE 5.0. Retrieved on 2010-08-12..

Advantages

The benefits of using java.util.concurrent package for developers include <ref name="Concurrent Programming with J2SE 5.0"> Qusay H. Mahmoud. Concurrent Programming with J2SE 5.0. Retrieved on 2010-08-12. Shorter and less messy application code Faster application implementation on schedule More scalable in data synchronization More readability and writ ability for development and debugging Easier maintenance

Unsolved Issue

Java concurrent package is not god. The common concurrent programming issue remains unresolved. Java concurrent package still does not ensure there won’t be any deadlock or CPU starvation in an application. It is developers’ responsibilities to take appropriate actions to handle the concurrency and data synchronization in their applications.

Links

Java Concurrency in Practice

Lesson: Concurrency

Java Technology

References

  1. Gary Shute. Java Synchronization. Retrieved on 2010-08-12.
  2. J2SE API v1.4.2. Retrieved on 2010-08-12.
  3. 3.0 3.1 Unknown. Problems with Java 1.4 synchronization model. Retrieved on 2010-08-12.
  4. V.K., Garg (September 2005). "A Critique of Java for Concurrent Programming". IEEE Computer Society 6 (9). Retrieved on 2010-08-12. [e]
  5. 5.0 5.1 J2SE API v5.0. Retrieved on 2010-08-12.
  6. 6.0 6.1 6.2 6.3 6.4 public class: CountDownLatch. Retrieved on 2010-08-12.
  7. 7.0 7.1 Qusay H. Mahmoud. Concurrent Programming with J2SE 5.0. Retrieved on 2010-08-12.