Home | Contact Us | FAQ | Search & Site Map | Link to Us
Sign In | Join | Other 45 Sites in Network
HomeAnnouncementsWhite Papers
Discussion GroupsFirst AidDatabasesJavaBeansGUIJava 3DVirtual MachineCORBASecurityToolsGeneral
Java DirectoryOpen Source ProjectsSample Book ChaptersUser GroupsWeb Resources
Related Topics
Databases.NETMore Topics ...

Java Forum / General / March 2007

Tip: Looking for answers? Try searching our database.

Concurrency problem

Thread view: 
Mr B - 12 Mar 2007 11:41 GMT
Hi,
I'm developing an application that uses a Collection class to store an
array of objects which specifies several operations, such as
addtoCollection, deletefromCollection, displayCollection etc.  The
problem is, I want several instances of these collections where items
can be inserted and deleted much similar to the producer consumer
problem.  Each collection has its own array and operations can be
performed on these arrays concurrently by concurrently executing
threads of producers and consumers for example.  This is fine, only
until a display thread is called, where it can be interupted midway
through outputting the contents of a collection which I don't want.  I
know that by making it syncronized this would work but I have no idea
what this entails, could synchronized be used for this method only, I
don't want all the other methods to have to be synchronized if
possible.

example of code is shown below:

Best Regards,

Daniel

public class Collection {
   //code omitted

   private int TraderID;
   private Trade [] body;
   public Semaphore mutex = new Semaphore(1);
   public Semaphore numAvail = new Semaphore(0);
   public Semaphore numFree;

   public Collection(int traderId, int size){
       //code omitted     }

   public int findMatch(Trade item)
   {
       //code omitted
   }

   public void displayCollection(){
       try {
           mutex.acquire();
       } catch (InterruptedException ex2) {
           System.out.println("mutex exception on aquire by
producer");
       }

       System.out.println("Collection
----------------------------------");
       for (int i=0; i<body.length; i++) {
           if (body[i]!=null){
               System.out.println(body[i].getTradeID());
           }
           else {
               System.out.println("Empty");
           }
       }
       mutex.release();
   }

   public void addtoCollection(Trade item){
      //code omitted
   }

   public Trade removefromCollection(int tradeNum){
      //code omitted
 }
}
Gordon Beaton - 12 Mar 2007 12:52 GMT
> Each collection has its own array and operations can be performed on
> these arrays concurrently by concurrently executing threads of
[quoted text clipped - 5 lines]
> I don't want all the other methods to have to be synchronized if
> possible.

If you only synchronize the display method, then only the display
method will obey the synchronization. If you want to prevent updates
while displaying, then the methods for updating need to be
synchronized as well.

You don't need explicit semaphores to achieve this, it's sufficient in
this case to simply declare the appropriate methods with the
synchronized keyword, which causes them to be mutually exclusive with
respect to the object they're called on (i.e. "this").

You can get more advanced behaviour by using reader/writer locks, but
the added complexity seems overkill for this simple example.

/gordon

Signature

[ don't email me support questions or followups ]
g o r d o n  +  n e w s  @  b a l d e r 1 3 . s e

Daniel Pitts - 12 Mar 2007 19:55 GMT
> > Each collection has its own array and operations can be performed on
> > these arrays concurrently by concurrently executing threads of
[quoted text clipped - 24 lines]
> [ don't email me support questions or followups ]
> g o r d o n  +  n e w s  @  b a l d e r 1 3 . s e

Actually, its more complicated than this...

If thread A reads property P, and thread B writes property P, then
both thread A AND thread B MUST use some form of synchronization.  It
is incorrect not to.  The java memory model allows threads to have
their own copy of core memory, and it is only flushed during
synchronization.  thread B could update P many times, but A isn't
guarantied to see any of it.  Worse, it could see the updates in an
unpredictable order, including partial updates etc...

I recommend the book Java Concurrency In Practice.
<http://www.javaconcurrencyinpractice.com/>
It gives you all the details you need to write a robust and correct
multithreaded application.
Mr B - 13 Mar 2007 13:04 GMT
Thanks alot for the response guys.  Well what I want to acheive is the
ability for concurrently executing threads to insert records into
various different collections at the same time.  A thread to also deal
with displaying the collection at any time to the user, but a snapshot
of the collection at that time, so I understand that this method
should have exclusive access to the collection, so things cannnot be
inserted, and be syncronized so the same method cannot be called by
another thread, breaking up the output with output from another
display thread.  If this can be achieved with sychronize aswell then I
will look into doing this, but wouldn't semaphores be safer?
Semaphores that can manage the number of free slots available and
mutually exclusive access aswell?  How could sychronize manage manage
the number of free spaces, would a semaphore be used here?

> If thread A reads property P, and thread B writes property P, then
> both thread A AND thread B MUST use some form of synchronization.

Is this not achieved with a mutual exclusion semaphore on the
collection of properties?

Thanks alot for your advice.

Regards,
Daniel
Mr B - 13 Mar 2007 14:50 GMT
Thanks for the response to this post.  I am trying to keep the program
as concurrent as possible, whilst keeping it as simple as possible.  I
have a few classes that extend the Thread class and I generate
instances of these classes in a Driver class.  These classes include
Enter, Remove, Display, for example.  The Collection class is used to
store the data these threads will add and remove to, and therefore has
methods which these threads can call to accomplish their
transactions.  I tried to synchronize the Display method but it never
seemed to work, and then I realised that it will need to be static.  I
then changed it to static, and my mutex, and all data-variables in the
class then needed to be static, can somebody explain I understand that
static means a single instatiation of the method, but why does its
variables also need to static.  This won't work for my program as I
need there different Collection class instances to have seperate
arrays for storing their own elements.  I'm a bit confised, if anyone
could explain that would be great.

> If thread A reads property P, and thread B writes property P, then
> both thread A AND thread B MUST use some form of synchronization.  It
> is incorrect not to.

Does my mutual exlusion semaphore not guarantee this?

Thanks
Daniel
Daniel Pitts - 13 Mar 2007 19:01 GMT
> Thanks for the response to this post.  I am trying to keep the program
> as concurrent as possible, whilst keeping it as simple as possible.  I
[quoted text clipped - 21 lines]
> Thanks
> Daniel

It guarantees it only if your collection modifying code ALSO acquires
the mutex. Since you snipped that code, I can make no assumptions.

There is a Lock designed for this.
<http://java.sun.com/j2se/1.5.0/docs/api/java/util/concurrent/locks/
ReadWriteLock.html>
This lets any number of Readers acquire a lock, OR exactly one
writer.  this is probably what you want.

Or, look into ConcurrentHashMap, This is a thread-safe alternative to
HashMap, and is probably faster than using Mutex of any sort,
depending on number of threads and contention levels.

Hope this helps,
Daniel (also)
Mark Space - 12 Mar 2007 17:20 GMT
> Hi,
> I'm developing an application that uses a Collection class to store an
[quoted text clipped - 7 lines]
> until a display thread is called, where it can be interupted midway
> through outputting the contents of a collection which I don't want.  I

What Gordon said.  You should probably just synchronize all methods for
this object, since any access (ie, access by a Reader) can potentially
be interrupted by an update.  Do you know about synchronized
collections?  They're a standard Java feature, you might want to use one
here.


Free Magazines

Get these publications absolutely FREE for up to 12 months. There are no hidden fees and no obligation. Simply choose a title, complete the application form and submit it. Read more ...

Oracle MagazineNetwork ComputingComputer WorldBio-IT WorldeWeekInformation WeekInfosecurity
 
Sign In
Join
My Latest Posts
My Monitored Threads
My Blog
My Photo Gallery
My Profile
My Homepage

Start New Thread
Enable EMail Alerts
Rate this Thread



©2008 Advenet LLC   Privacy Policy - Terms of Use
This website includes both content owned or controlled by Advenet as well as content owned or controlled by third parties.