Home | Contact Us | FAQ | Search & Site Map | Link to Us
Sign In | Join | Other 45 Sites in Network
HomeAnnouncementsWhite Papers
Discussion GroupsFirst AidDatabasesJavaBeansGUIJava 3DVirtual MachineCORBASecurityToolsGeneral
Java DirectoryOpen Source ProjectsSample Book ChaptersUser GroupsWeb Resources
Related Topics
Databases.NETMore Topics ...

Java Forum / General / February 2008

Tip: Looking for answers? Try searching our database.

SCJP Threading question - locking on a String object

Thread view: 
lielar - 26 Feb 2008 12:26 GMT
Hi

Still stuck on threading question. (Someone will probably recognise
this)

I have the following thread class
<snip>-------------------------------------------------------
class MBThread extends Thread {
String name;
OrderedThread orderT;
  MBThread(String name, OrderedThread orderT) {
         this.name = name;
         this.orderT = orderT;
  }

  public void run() {
       orderT.display(name);
  }

}

public class MBTHread {
     public void display(String msg) {
            synchronized(msg) {
                  for (int i=0; i<20; i++) {
                       System.out.println("Name= "+msg);
                   }
            }

      }

     public static void main(String [] args) {
            OrderedThread orderedT = new OrderedThread();
            MBThread first = new MBThread("One", orderedT);
            MBThread second = new MBThread("Two", orderedT);
            first.start();
            second.start();
     }
}
<snip>-------------------------------------------------------

My Questions
--------------------
1) Here the string object is synchronised. What is the difference
between the string reference being synchronised as opposed to the
whole method? Does it mean that any thread can access the method but
only one thread can access the object?
2) If I synch another object would the outcome be different if it is
mutable (unlike String)?
3) What is the difference between synching the instance, the class
(MBThread.class), an object, and method?

Thanks
Eric Sosman - 26 Feb 2008 17:02 GMT
> Hi
>
[quoted text clipped - 6 lines]
> String name;
> OrderedThread orderT;

    What's an OrderedThread?  It doesn't seem to have
any essential role in the code or on your questions;
I'm just curious.

>    MBThread(String name, OrderedThread orderT) {
>           this.name = name;
[quoted text clipped - 33 lines]
> whole method? Does it mean that any thread can access the method but
> only one thread can access the object?

    Synchronization always uses an object instance.  The
object's lock ("monitor") is acquired before the stretch
of synchronized code starts executing, and is held throughout
its execution.  Since only one thread at a time can hold a
particular object's lock, only one thread at a time can be
executing a piece of code that is synchronized on that object.

    Your code identifies the locked object explicitly: it
is the object referred to by the msg argument of the display
method.  As it happens, this will be the String object "One"
in one thread and the String object "Two" in the other; these
are different objects, so they can be locked and unlocked
independently; the two threads do not get in each other's
way.  (Not in this code, anyhow: The methods of System.out
most likely have additional synchronization, and the two
threads might squabble over locks while printing output.)

    When you apply `synchronized' to an entire method you
can omit the specification of which object's lock should be
used.  If you do, Java assumes you mean the method's `this'
object (for a static method, where there is no `this', Java
assumes you mean the class' Class object).  Everything works
just as above, except that a different object is locked
while the synchronized method runs.

> 2) If I synch another object would the outcome be different if it is
> mutable (unlike String)?

    The object's mutability or immutability makes no difference.
The object's *identity* might make a difference, in the sense
that if both threads synchronize on the same object they will
affect each other's progress.

> 3) What is the difference between synching the instance, the class
> (MBThread.class), an object, and method?

    For the first three, it's just a matter of which object's
lock is held while the synchronized code executes: the `this'
object, or a Class object, or some other object.  The fourth
isn't really answerable: you don't "synchronize on a method,"
you "synchronize on some object while executing a method."

Signature

Eric.Sosman@sun.com

lielar - 27 Feb 2008 02:02 GMT
Hi

Thanks for the reply.

Please elaborate on point 3.

What is the difference between in the sync block if I do,

sync(MBThread.class) {

}

as opposed to what it is now?

What does it mean that the thread has to get a lock on the Class as
opposed to an instance
(eg

sync(this) {

}
)

or the object 'msg'

sync(msg) {

}
?

Would the output be different?

Cheers
Patrick

> > Hi
>
[quoted text clipped - 93 lines]
> --
> Eric.Sos...@sun.com
Mark Space - 27 Feb 2008 02:29 GMT
> What is the difference between in the sync block if I do,
>
> sync(MBThread.class) {

> sync(this) {

The first one is a class.  The second one is an instantiated object.  If
you have a class MBThread, you can make many MBThread objects.

MBThread t1 = new MBThread();
MBThread t2 = new MBThread();
MBThread t3 = new MBThread();

These are different objects with different locks.  Calling a
synchronized method in t1 (you have none, but pretend there is) will
lock t1 but not t2 or t3.  That's because once t1 is instantiated its
this pointer points to t1 and nothing else.

There is only one MBThread.class in a program (let's not get into
classloaders).  It's a singleton.  Since there's only one object there's
only one lock and taking it will stop anything else that also tries to
synchronize on the same lock (a static method for example).
Eric Sosman - 27 Feb 2008 16:02 GMT
> Hi
>
> Thanks for the reply.

    You're welcome, but please learn not to top-post.

> Please elaborate on point 3.
>
[quoted text clipped - 11 lines]
>
> sync(this) {

    It's `synchronized', not `sync'.

    The difference is in which object's lock is used.  There
is a Class object for every loaded class, and the first
example synchronizes on the Class object for the MBThread
class.  The second synchronizes on whatever object `this'
refers to.  That's the only difference.

    If you haven't already read the Concurrency chapter in
the Java Tutorial, this might be a good time to do so.

http://java.sun.com/docs/books/tutorial/essential/concurrency/

Signature

Eric.Sosman@sun.com



Free Magazines

Get these publications absolutely FREE for up to 12 months. There are no hidden fees and no obligation. Simply choose a title, complete the application form and submit it. Read more ...

Oracle MagazineNetwork ComputingComputer WorldBio-IT WorldeWeekInformation WeekInfosecurity
 
Sign In
Join
My Latest Posts
My Monitored Threads
My Blog
My Photo Gallery
My Profile
My Homepage

Start New Thread
Enable EMail Alerts
Rate this Thread



©2008 Advenet LLC   Privacy Policy - Terms of Use
This website includes both content owned or controlled by Advenet as well as content owned or controlled by third parties.