• 1 reply
  • Latest Post - ‏2008-03-13T10:36:48Z by SystemAdmin
757 Posts

Pinned topic Synchronization question.

‏2008-03-08T07:44:54Z |
Hi again!
Sorry for dumbish question, but...

Let say I using concurrent HashTable from java.utils.concurrent package. Objects inside it are changable by multiple threads. Do I have synchronize objects itself?
ConcurrentHashtable table = new ConcurrentHashtable ();
(Thread A)--> SomeObject obj = tablesomeKey;
(Thread B)--> SomeObject obj = tablesomeKey;

In this example, do I have to synchronize obj?

Updated on 2008-03-13T10:36:48Z at 2008-03-13T10:36:48Z by SystemAdmin
  • SystemAdmin
    757 Posts

    Re: Synchronization question.

    It is not quite clear, what you mean but...

    Let's suppose you have the following class:

    class SomeClass {
    private int a;

    public SomeClass(int a) { this.a = a; }
    public void increment() { a++; }
    public void decrement() { a--; }

    public void prn() { System.out.println("a=" + a);

    Then , let's say in main(), you do:

    SomeClass sc = new SomeClass(1);
    Vector v = new ... // in this particular case it doesn't matter if this is a vector
    // or ConcurrentHashMap


    Placing object to a synchronized/concurrent collection ensures only safe-publication:
    if thread A tries to get 'sc', it is only guaranteed that A will see state of 'sc' as
    it was published (put in the collection) in the main(). In other words:

    // Thread A
    SomeClass tmp = v.get_sc_somehow();
    tmp.prn(); -> will print out 1;

    If then thread A does:
    // Thread A
    tmp.increment(); // sc now is 3

    and another thread does:
    // Thread B

    SomeClass tmp2 = v.get_sc_somehow();
    tmp2.prn(); -> result is unpredictable: can be 1 or 2 or 3

    To fix this problem your (mutable) class must be thread safe. The simplest way (but, not the best one)
    is to make all methods of SomeClass (in this particular case) synchronized. Other solutions are
    possible, but this is a different story.

    So the answer to you question: if you are going to use mutable objects and change their state from
    different threads - your objects must be thread-safe. You can find more on this in "Java Concurrency in Practice" book by Brian Goetz, chapter 3: Sharing objects.

    Cheers, and there are no dumb questions...
    Updated on 2008-03-13T10:36:48Z at 2008-03-13T10:36:48Z by SystemAdmin