• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 1095
  • Last Modified:

when do I need the synchronized attribute?

I have a class that has member variables, and has Get/Set accessor methods for each variable. For example:

class MyClass {
   private String    _myStr;
   private Hashtable _myHash;

   ...
   public synchronized SetString(String strNewStr) {
      _myStr = strNewStr;
   }
   public synchronized GetString() {
      return _myStr;
   }

   public synchronized SetHash(Hashtable strNewHash) {
      _myHash = strNewHash;
   }
   public synchronized GetHash() {
      return _myHash;
   }
}

This seems like overkill to me. The only thing I'm getting by having the Get/Set methods is the synchronization control. It seems like JAVA should already have a lower level of synchronization control on the String or Hashtable objects (or whatever object I have in my class). Is this true? Or do I need to keep the Get/Set methods?

Thanks,

Paul Ostrowski
0
postrowski
Asked:
postrowski
  • 5
  • 2
  • 2
  • +3
1 Solution
 
bagi112599Commented:
I don't think you will need synchronized for cases above.
Because each of these methods are only one line of code that are atomic. However you will need synchronized,if you were doing something lengthy in say, setString() and _myStr is shared among threads.
0
 
postrowskiAuthor Commented:
so does that mean that what we see as one line of code in JAVA source will always be atomic?
What about a more complex accessor such as:

   public int incRefCount() {
      return ++_refCount;
   }
or
   public int incRefCount() {
      return _refCount++;
   }

this is one line of code, but there are definately two operations occuring.
0
 
exorcistCommented:
BE CAREFUL!
wether you need "synchronized" or not, does NOT depend on your method length. You don't need to synchronize your get... methods, and in this case you don't even need to synchronize your set... methods.

Let me give you an example where you need "synchronized":

int counter = 0;

public synchronized void increase() {

  counter++;
  if (counter == 20)
    counter = 0;
}

In this case let's imagine counter is set to 19 sometime. Two threads are calling this method ON THE SAME instance. If you are unlucky (and the method was not synchronized), threads could be changed right after counter++;. So counter++ is executed for the one thread and then for the other thread. So now, counter is set to 21. BANG!
If you synchronize this method, the second thread could not by any chance enter this method on the same object as long as the first thread did not terminate this method.

And btw, as far as I know, the Hashtable class is highly synchronized. ArrayList is not, and thus ArrayList should be preferred if you don't need to worry about synchronization.

Hope this helps,
  the Java Exorcist
0
Industry Leaders: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

 
postrowskiAuthor Commented:
I understand why 'synchronize' needs to be used, but I'm still a little shaky on this one implication:
are all JAVA source code statements (that is, text that appears between two semi-colons ';') executed as atomic operations?

back to my follow-up comment:
  public int incRefCount() {
     return _refCount++;
  }
can I be gaurenteed that the compiler didn't see this as:
  public int incRefCount() {
     int temp = _refCount;
     _refCount++;
     return temp;
  }
If it did and two threads called incRefCount at the same time it is possible (granted, VERY unlikely) that the two threads could be returned the same value (the initial value of _refCount before anything was called).
0
 
imladrisCommented:
No. You cannot assume that a single Java statement is an atomic operation.
0
 
postrowskiAuthor Commented:
OK, if I can't assume that all single Java statements are atomic operations, can I at least assume that simple assignment operations and return operations are atomic? (as in the first code I present, not the refCount code I added later.)
If not, then I would need to have the get/set methods I first described. Otherwise, I can just make the member variables public and access them directly. Right?
0
 
objectsCommented:
If a method can change the state of your object, and can be accessed concurrently by two or more threads then it should be synchronized.
So in your example the two Set methods would need to be synchronized, but the Get's do not.
Personally would never make assumptions about what's an atomic operation and what's not as this is defined by the machine code generated by the compiler.
0
 
postrowskiAuthor Commented:
objects, your comment makes no sense to me. If the Set and get operations are truely atomic, then there is no need to be synchronized. However, if either one is not atomic, then they both need to be synchronized. Consider this. during the non-atomic Set operation (which is synchronized) a thread switch occurs after 50% of the data has been modified. The new thread is now free to call Get on the data, but it will return garbage because half the data is new, and half is old.
Either they both need to be synchronized, or they both don't.
0
 
bagi112599Commented:
>>are all JAVA source code statements (that is, text that appears between two semi-colons ';') executed
as atomic operations?
absolutely not, look at this:
cnt = increase();

public int increase() {

 counter++;
 if (counter == 20)
   counter = 0;
}

but
sybchronized{cnt = increase();}
is OK, even if increase is not synchronized.
It is more safe to use synchronized more often, but
it has penalty on performance.
>>, can I at least assume that
simple assignment operations and return operations are atomic?
yes, I believe so.
0
 
postrowskiAuthor Commented:
I haven't recieved a very definate answer on this from this group, but I did manage to find the perfect answer at
http://www-106.ibm.com/developerworks/library/praxis/pr50.html.
It is a very good article, and I think everyone that has posted to this question will find it very useful.
Thanks for all your help.
0
 
objectsCommented:
Good to hear you have a full understanding of the topic, I'll come to you if I ever have a question about thread synchronisation.
0
 
sudhakar_koundinyaCommented:
No comment has been added lately, so it's time to clean up this TA.
I will leave a recommendation in the Cleanup topic area that this question is:


[paq'ed and points refunded]


Please leave any comments here within the next seven days.
 
PLEASE DO NOT ACCEPT THIS COMMENT AS AN ANSWER!
 
sudhakar_koundinya
EE Cleanup Volunteer
---------------------
If you feel that your question was not properly addressed, or that none of the comments received were appropriate answers, please post your concern in THIS thread.
0

Featured Post

Important Lessons on Recovering from Petya

In their most recent webinar, Skyport Systems explores ways to isolate and protect critical databases to keep the core of your company safe from harm.

  • 5
  • 2
  • 2
  • +3
Tackle projects and never again get stuck behind a technical roadblock.
Join Now