Welcome to the Java Programming Forums


The professional, friendly Java community. 21,500 members and growing!


The Java Programming Forums are a community of Java programmers from all around the World. Our members have a wide range of skills and they all have one thing in common: A passion to learn and code Java. We invite beginner Java programmers right through to Java professionals to post here and share your knowledge. Become a part of the community, help others, expand your knowledge of Java and enjoy talking with like minded people. Registration is quick and best of all free. We look forward to meeting you.


>> REGISTER NOW TO START POSTING


Members have full access to the forums. Advertisements are removed for registered users.

Results 1 to 12 of 12

Thread: Object o = new Object(); need help

  1. #1
    Junior Member
    Join Date
    May 2009
    Posts
    14
    Thanks
    1
    Thanked 0 Times in 0 Posts

    Default Object o = new Object(); need help

    There is a server class in which we are using this code. I just want to ask, what this code do in general??

    Object o = new Object();
    synchronized (o) {
    try {
    o.wait();
    } catch (InterruptedException ex) {}


  2. #2
    Super Moderator helloworld922's Avatar
    Join Date
    Jun 2009
    Posts
    2,896
    Thanks
    23
    Thanked 619 Times in 561 Posts
    Blog Entries
    18

    Default Re: Object o = new Object(); need help

    hmm... I'm not so good with multi-threaded code, but I think it creates an Object o, then tells o to wait until it's been notified. The synchronized means that only one thread has access to it's guts at any one time.

  3. #3
    Super Moderator Json's Avatar
    Join Date
    Jul 2009
    Location
    Warrington, United Kingdom
    Posts
    1,274
    My Mood
    Happy
    Thanks
    70
    Thanked 156 Times in 152 Posts

    Default Re: Object o = new Object(); need help

    Do be able to have a synchronized block without synchronizing the whole method you have to sync on a certain object. When you do that you create a lock and the next thread which calls that method and reaches that sync block will have to wait until the lock on the object has been released.

    So to create a shortcut for object locking you can just create an object like in the code and sync on that object.

    However if that object it created inside the actual method that has the sync block it will effectively be useless because every time the method is called there will be a new object used as a lock so no matter what thread calls this method you wont be seeing a synchronized behaviour.

    If the object is declared as a static it would make more sense or if its an object passed into the thread at creation, as long as all threads share the same object they lock on it should work.

    Here is a simple test for you. Play around with this code and you will understand how the locks work.

    public class ThreadTest1 extends Thread {
     
        private static Object object = new Object();
     
        private static int value = 0;
     
        public ThreadTest1(final String name) {
            super(name);
        }
     
        public static void main(final String... arguments) {
            for (int i = 1; i <= 15; ++i) {
                new ThreadTest1("ThreadTest_" + i).start();
            }
        }
     
        @Override
        public void run() {
            myFirstMethod();
     
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
     
            mySecondMethod();
        }
     
        private void myFirstMethod() {
            final Object object = new Object();
     
            synchronized (object) {
                value = value + 1;
     
                try {
                    Thread.sleep(500);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
     
                System.out.println("This is myFirstMethod called from thread [" + Thread.currentThread().getName() + "] with value [" + value + "]");
            }
        }
     
        private void mySecondMethod() {
            synchronized (object) {
                value = value + 1;
     
                try {
                    Thread.sleep(500);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
     
                System.out.println("This is mySecondMethod called from thread [" + Thread.currentThread().getName() + "] with value [" + value + "]");
            }
     
        }
    }


    When it comes to waiting on the object, this is also rather pointless if the object is only on the stack (in a method). That would put the thread in a permanent RUNNABLE state waiting for someone to notify on the object which can never happen.

    // Json

  4. #4
    Junior Member
    Join Date
    May 2009
    Posts
    14
    Thanks
    1
    Thanked 0 Times in 0 Posts

    Default Re: Object o = new Object(); need help

    i understand your point json and helloworld . I have a code, got it from internet. I am just trying to understand this code. here they have created Object object in constructor. why ? what is its function?? doest it mean that this object will lock the constructor, if yes, how we can unlock it ??
    public class Server {
     
        static final String USAGE = "java bankrmi.Server <bank_rmi_url>";
        static final String BANK = "World Bank";
     
        public Server(String[] args) {
    	String bankname = (args.length > 0)? args[0] : BANK;	
    	if (args.length > 1 || bankname.equalsIgnoreCase("-h")) {
    	    System.out.println(USAGE);
    	    System.exit(1);
    	}	
    	try {
    	    Bank bankobj = new BankImpl(bankname);
    	    java.rmi.Naming.rebind(bankname, bankobj);
    	    System.out.println(bankobj + " is ready.");
    	} catch (Exception e) {
    	    System.out.println(e);
    	}
            Object o = new Object();
            synchronized (o) {
                try {
                    o.wait();
                } catch (InterruptedException ex) {}
            }
        }
            public static void main(String[] args) {
                new Server(args);
            }
    }

    //Zeeshan
    Last edited by helloworld922; October 8th, 2009 at 07:44 PM.

  5. #5
    Super Moderator helloworld922's Avatar
    Join Date
    Jun 2009
    Posts
    2,896
    Thanks
    23
    Thanked 619 Times in 561 Posts
    Blog Entries
    18

    Default Re: Object o = new Object(); need help

    Maybe you should take a look at this:
    Synchronized Statements

    The only thing I can think of is that wait causes the current thread to wait until o.notify() or o.notifyAll() are called. However, since it's impossible for any other object to gain access to that specific o object, the thread will be waiting indefinitely... The synchronized block comes because the object must own the intrinsic lock of o in order to invoke the o.wait() method (which, releases the intrinsic lock for other to use, but no one else can use it as the code is because no other thread has the reference to that specific o object).

    Are you sure this code is correct, or did you need help fixing it? If so, what is it you need this code to do?

  6. #6
    Super Moderator Json's Avatar
    Join Date
    Jul 2009
    Location
    Warrington, United Kingdom
    Posts
    1,274
    My Mood
    Happy
    Thanks
    70
    Thanked 156 Times in 152 Posts

    Default Re: Object o = new Object(); need help

    In a stupid way its like doing this.

    while(true){}

    Or.

    for(;;) {}

    Or any other infinite loops just to keep the thread alive.

    // Json

  7. #7
    Junior Member
    Join Date
    May 2009
    Posts
    14
    Thanks
    1
    Thanked 0 Times in 0 Posts

    Default Re: Object o = new Object(); need help

    you mean in my code example o.wait( ) is just for keeping the thread alive ??

    //zeeshan

  8. #8
    Super Moderator helloworld922's Avatar
    Join Date
    Jun 2009
    Posts
    2,896
    Thanks
    23
    Thanked 619 Times in 561 Posts
    Blog Entries
    18

    Default Re: Object o = new Object(); need help

    Yes, but the special thing about wait is that the CPU is not being fully utilized to perform that task, where as an infinite while/for loop is maxing out your CPU. I still think it's kind of weird... At some point, there needs to be something that can safely end that thread.

  9. #9
    Junior Member
    Join Date
    Oct 2009
    Posts
    1
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default Re: Object o = new Object(); need help

    How great your info is!But Can you give some more sample questions and answers.I really want to get more info about this topicIt really useful for me. Thanks.

  10. #10
    Member
    Join Date
    Oct 2009
    Posts
    52
    Thanks
    0
    Thanked 6 Times in 5 Posts

    Default Re: Object o = new Object(); need help

    Look for the book Java Concurrency in Practice by Brian Goetz.

  11. #11
    Super Moderator Json's Avatar
    Join Date
    Jul 2009
    Location
    Warrington, United Kingdom
    Posts
    1,274
    My Mood
    Happy
    Thanks
    70
    Thanked 156 Times in 152 Posts

    Default Re: Object o = new Object(); need help

    bibcloax, what exactly more would you like help on, threads or stupid while loops to keep threads alive?

    // Json

  12. #12
    Junior Member
    Join Date
    Jan 2010
    Posts
    1
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default Re: Object o = new Object(); need help

    Quote Originally Posted by literallyjer View Post
    Look for the book Java Concurrency in Practice by Brian Goetz.
    Thanks all for contributing to this thread. Lots to read in this forum but I like it.

Similar Threads

  1. Arraylist or Arraylist Object?
    By igniteflow in forum Collections and Generics
    Replies: 2
    Last Post: September 11th, 2009, 02:08 AM