Solved

when do I need the synchronized attribute?

Posted on 2001-06-11
12
1,066 Views
Last Modified: 2012-06-27
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
Comment
Question by:postrowski
  • 5
  • 2
  • 2
  • +3
12 Comments
 
LVL 2

Expert Comment

by:bagi112599
Comment Utility
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
 

Author Comment

by:postrowski
Comment Utility
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
 
LVL 3

Expert Comment

by:exorcist
Comment Utility
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
 

Author Comment

by:postrowski
Comment Utility
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
 
LVL 16

Expert Comment

by:imladris
Comment Utility
No. You cannot assume that a single Java statement is an atomic operation.
0
 

Author Comment

by:postrowski
Comment Utility
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
Maximize Your Threat Intelligence Reporting

Reporting is one of the most important and least talked about aspects of a world-class threat intelligence program. Here’s how to do it right.

 
LVL 92

Expert Comment

by:objects
Comment Utility
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
 

Author Comment

by:postrowski
Comment Utility
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
 
LVL 2

Expert Comment

by:bagi112599
Comment Utility
>>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
 

Accepted Solution

by:
postrowski earned 0 total points
Comment Utility
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
 
LVL 92

Expert Comment

by:objects
Comment Utility
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
 
LVL 14

Expert Comment

by:sudhakar_koundinya
Comment Utility
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

What Should I Do With This Threat Intelligence?

Are you wondering if you actually need threat intelligence? The answer is yes. We explain the basics for creating useful threat intelligence.

Join & Write a Comment

Suggested Solutions

For customizing the look of your lightweight component and making it look lucid like it was made of glass. Or: how to make your component more Apple-ish ;) This tip assumes your component to be of rectangular shape and completely opaque. (COD…
Introduction This article is the last of three articles that explain why and how the Experts Exchange QA Team does test automation for our web site. This article covers our test design approach and then goes through a simple test case example, how …
Viewers learn about the third conditional statement “else if” and use it in an example program. Then additional information about conditional statements is provided, covering the topic thoroughly. Viewers learn about the third conditional statement …
This video teaches viewers about errors in exception handling.

772 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

11 Experts available now in Live!

Get 1:1 Help Now