user2467899
user2467899

Reputation: 575

Thread-safe classes explanation in Java

Let's consider this situation:

public class A {
    private Vector<B> v  = new Vector<B>();
}

public class B {
    private HashSet<C> hs = new HashSet<C>();
}

public class C {
    private String sameString;

    public void setSameString(String s){
          this.sameString = s;
    }
}

My questions are:

  1. Vector is thread-safe so when a thread calls over it, for instance, the get(int index)method Is this thread the only owner ofHashSeths?

  2. If a thread call get(int index) over v and it obtains one B object. Then this thread obtains a C object and invoke setSameString(String s) method, is this write thread-safe? Or mechanism such as Lock are needed?

Upvotes: 0

Views: 61

Answers (2)

qqibrow
qqibrow

Reputation: 3022

In case 2. It's not thread-safe because multiple threads could visit the data at the same time. Consider using read-write lock if you want to achieve better performance. http://docs.oracle.com/javase/7/docs/api/java/util/concurrent/locks/ReadWriteLock.html#readLock()

Upvotes: 0

Giovanni Botta
Giovanni Botta

Reputation: 9816

First of all, take a look at this SO on reasons not to use Vector. That being said:

1) Vector locks on every operation. That means it only allows one thread at a time to call any of its operations (get,set,add,etc.). There is nothing preventing multiple threads from modifying Bs or their members because they can obtain a reference to them at different times. The only guarantee with Vector (or classes that have similar synchronization policies) is that no two threads can concurrently modify the vector and thus get into a race condition (which could throw ConcurrentModificationException and/or lead to undefined behavior);

2) As above, there is nothing preventing multiple threads to access Cs at the same time because they can obtain a reference to them at different times.

If you need to protect the state of an object, you need to do it as close to the state as possible. Java has no concept of a thread owning an object. So in your case, if you want to prevent many threads from calling setSameString concurrently, you need to declare the method synchronized.

I recommend the excellent book by Brian Goetz on concurrency for more on the topic.

Upvotes: 4

Related Questions