Want to win a PS4? Go Premium and enter to win our High-Tech Treats giveaway. Enter to Win

x
?
Solved

when do I need the synchronized attribute?

Posted on 2001-06-11
12
Medium Priority
?
1,090 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
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 5
  • 2
  • 2
  • +3
12 Comments
 
LVL 2

Expert Comment

by:bagi112599
ID: 6179102
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
ID: 6179129
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
ID: 6179221
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
VIDEO: THE CONCERTO CLOUD FOR HEALTHCARE

Modern healthcare requires a modern cloud. View this brief video to understand how the Concerto Cloud for Healthcare can help your organization.

 

Author Comment

by:postrowski
ID: 6179257
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
ID: 6179363
No. You cannot assume that a single Java statement is an atomic operation.
0
 

Author Comment

by:postrowski
ID: 6179377
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
 
LVL 92

Expert Comment

by:objects
ID: 6179509
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
ID: 6182370
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
ID: 6182528
>>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
ID: 6182626
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
ID: 6183756
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
ID: 9027555
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

Free Tool: ZipGrep

ZipGrep is a utility that can list and search zip (.war, .ear, .jar, etc) archives for text patterns, without the need to extract the archive's contents.

One of a set of tools we're offering as a way to say thank you for being a part of the community.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Java contains several comparison operators (e.g., <, <=, >, >=, ==, !=) that allow you to compare primitive values. However, these operators cannot be used to compare the contents of objects. Interface Comparable is used to allow objects of a cl…
Introduction Java can be integrated with native programs using an interface called JNI(Java Native Interface). Native programs are programs which can directly run on the processor. JNI is simply a naming and calling convention so that the JVM (Java…
Viewers will learn about the regular for loop in Java and how to use it. Definition: Break the for loop down into 3 parts: Syntax when using for loops: Example using a for loop:
This video teaches viewers about errors in exception handling.
Suggested Courses

618 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