Thread Methods but in Object class, y?

Why wait, notify, notifyall methods are in object class instead of Thread class?

thechad wrote:
It's not clear to me why. Probably it's a historical artefact .. once it was in Object, it's hard to take it out.
You're question is a fair question it seems to me. Maybe someone will tell you there's a good reason.Yes, there is a very good reason and it's not a historical artifact.
wait / notify are used for locking in java. For instance, imagine you have a job queue, and you've got a whole bunch of worker threads that are getting jobs from it. What happens when the queue is empty and there are no more jobs? You want to wait for the queue to have more jobs. Then when a new job comes in, you want to notify any thread waiting that it can now proceed.
In fact, with reference to why isn't this just handled in thread, it is dangerous and wrong to call wait, notify or notifyall on a Thread object... Thread.join calls wait on the thread and thread death calls notifyAll, but API docs don't guarentee this so you should avoid these methods in a Thread object.

Similar Messages

  • Use of hashCode and equals method in java(Object class)

    What is the use of hashCode and in which scenario it can be used?similarly use of equals method in a class when it overides form Object class. i.e i have seen many scenario the above said method is overridden into the class.so why and in which scenario it has to override?Please help me.

    You could find that out easily with google, that is a standard junior developer interview question.

  • When do we override our own clone method not the Object class clone method

    Hi,
    I have a confusion in overriding clone method.We can create clone object by writing Object.clone() but some times I have seen writing our own clone method ,when do we write this,also clone() is defined protected and when we write our own clone it is said to write it public,why?
    Thanks
    Sumit

    protected methods can only be called in the same class and it subclass. You can make clone protected if this is all you need.
    However if you need to clone() the object from another class, it need to be public.
    This is the same for any method.
    Also as Object.clone() is protected you cannot make it private or package-local (this is true of any protected method)

  • Object Class -Thread

    Hai Respected Friend ,
    I have one doubt regarding Object Class. for what purpose the Object class has some methods like Notify(),Notify All(),wait() though we are not using those methods except with Thread class.
    why they are defined these methods in the Object Class ,why not in the Thread Class even though it is only useful with Thread Class.
    Please give clear ans.
    Thanks
    Selvakumar

    BigDaddyLoveHandles wrote:
    malcolmmc wrote:
    Actually, though these methods are useful only in a multi-threaded environment, no Thread objects are directly involved. What you need to specify isn't a thread object (the current thread is always the one affected) but the monitor, which can be any kind of Object.I would have been happy if they had defined a Lock class with wait and notify methods, because I prefer doing:
    public class C {
    private final Object lock = new Lock();
    public void method() {
    synchronized(lock) {...}
    }to
    public class C {
    public synchronized void method() {
    }In the second case, you have to contend with other code incorrectly calling wait/notify on an instance of C.
    So I don't see the win in these being java.lang.Object methods, other than allowing you to create one less object -- what an efficiency win ;-)However, there are times when it makes sense to expose the lock. For instance Collections.synchronizedXxx.

  • How do interfaces have methods of Object class

    Hi All,
    Please consider the following code snippet.
    public interface EmployeeService
        public void createEmployee(Employee emp);
        public Employee findEmployee(String empId);
    public class EmployeeServiceImpl implements EmployeeService
        public void createEmployee(Employee emp) { ................. }
        public Employee findEmployee(String empId) { ................. }
    }The above is a simple example where I have an employee object with two service methods to create and find an employee.
    Now the consider the following
    EmployeeService empService = new EmployeeServiceImpl();
    Employee emp = empService.findEmployee("1").So the above code helps me in finding an employee.
    Now, we know that you can only call those methods that are defined in the interface.
    My question is, if I use the empService you would be able to access the methods of the Object class (equals, hashCode, wait etc.)
    How does this happen? In the Jave API we know all class by default override the Object class, so how does it work with interfaces?
    Thanks in advance for the reply

    [JLS 6.4.4 The Members of an Interface Type|http://java.sun.com/docs/books/jls/third_edition/html/names.html#6.4.4] says:
    If an interface has no direct superinterfaces, then the interface implicitly declares a public abstract member method m with signature s, return type r, and throws clause t corresponding to each public instance method m with signature s, return type r, and throws clause t declared in Object, unless a method with the same signature, same return type, and a compatible throws clause is explicitly declared by the interface. It is a compile-time error if the interface explicitly declares such a method m in the case where m is declared to be final in Object.
    So, in short, those methods exist in interfaces because the JLS says they do.

  • Why notify() and notifyall() is in Object class

    pls help me
    why notify() and notifyall() methods which are related to thread are define in Object class,instead of defining in Thread class

    shouldn't be called on thread objects ever
    at all (one of my pet peeves with Java)Why not? It would make a nice entry in the IOJJJ (International
    Obfuscated Java Juggling Jamboree) if it existed ;-)First of all, sorry for my bad english. It's early here :)Nah, it's just a late a rainy Sunday afternoon here, so no problem ;-)
    Second of all, the way that Thread is implemented, at least on
    windows, it that calling Thread.join does a wait() on that thread object.
    Thus, if you call notify() on a thread, you could actually be waking up
    joined threads, which wouldn't be good. And if you called wait, you
    could get woken up if the thread finishes which violates the contract of
    wait and notify to some extent and also relies on an undocumented
    feature.I take back my previous remark: it could not just be a nice little entry in
    the IOJJJ, it would be a great entry in that contest! ;-)
    kind regards,
    Jos
    ps. your example is the first example that clearly gives a reason for
    spurious wakeups I've ever read; thanks; joined threads, I've got to
    remember that example. <scribble, scribble, scribble/> done. ;-)

  • Confusion with Object class

    We all know that all classes implements Object directly or indirectly. That is why we get all public methods available in Object class.
    But as the definition says, if our class extends Object class indirectly and we are able to get public methods like notify(), notifyAll() etc why are we unable to get the protected method clone() of this class even our class extends Object class??
    I mean to say either both type of methods must not be available or must be available.
    Hope I am clear about my issue??
    Can any of you guys explain it???
    Regards.

    Your class needs to implement Cloneable interface.
    For example this will throw an exception -
    public class TestClone {
              void foo() throws Exception {
              clone();
              public static void main(String args[]){
                   try {
                        new TestClone().foo();
                   }catch (Exception ex){
                        ex.printStackTrace();
    This will not -
    public class TestClone implements Cloneable{
              void foo() throws Exception {
              clone();
              public static void main(String args[]){
                   try {
                        new TestClone().foo();
                   }catch (Exception ex){
                        ex.printStackTrace();
    }

  • Calling a super.ssuper.method but your super is a abstract class.

    Dear guys,
    Is that possible to invoke your super's super's method but your super is a abstract class?
    like:
    class GO {   public void draw() { } }
    abstract class GORunner extends GO {}
    class GOCounter extends GORunner {
    public void draw() {
    super.super.draw();
    I want to do this because I would like to take advantages of the abstract as an layer to achieve some polymorphism programming Therefore, in the later stage of the programming some code may only refer to GORunner but actually it is holding a GOCounter object.
    Thank!!

    BTW you don't need to write this
    public void draw() {
       super.draw();
    }It works but its basically the same as not having it at all.

  • Why wait() is there in Object class why not in Thread class

    why wait() is there in Object class why not in Thread class .
    while we use wait() in the case of thread environment?
    If there is any situation where we use it without using threads please mention with example. or link to that example..

    839091 wrote:
    The question still remain un-answered as the answers provided are not clear. Can anybody explain why wait(), notify() methods are available in Object class and not thread?What part of the answers given did you not understand?
    Have you even tried writing any code that uses wait/notify and thought about how you'd write the same code if they existed only on Thread rather than on Object?
    Have you studied the basics of Java's multithreading?
    Do you know what a lock is?
    Do you know what the synchronized keyword does?
    Do you understand the relationship between synchronized and wait/notify?
    If you can answer yes to these questions, then the reason that wait/notify exist on Object should be obvious. So, which of the above are "no"?

  • Are methods in the Graphics class Thread Safe

    Can methods from the Graphics class (.e.g. drawImage(), drawString(), ect..) be called from any thread? In other words, can two threads that refer to the same Graphics object step on each other methods calls?
    TIA,
    DB
    Edited by: Darth_Bane on Apr 27, 2009 1:44 PM

    No,
    They are GUI activities so you should call them from the Swing Thread ( Event Disptach Thread)
    Now for the JComponent the following are thread safe:
    repaint(), revalidate, invalidate which can be called from any thread.
    Also the listener list can be modified from any thread addListenerXX or removeListenerXX where XX is ListenerType
    Regards,
    Alan Mehio
    London, UK

  • Why methods equals() and hashCode() is defined in Object Class?

    Why methods equals() and hashCode() is defined in Object Class?

    If you have two objects and you don't know (or care about) their exact types, but you still want to know if they are the same, then you can do something like this:
    Object o1 = getObject1();
    Object o2 = getObject2();
    if (o1.equals(o2)) {
      // they are the same, do something
    } else {
      // they are different, do something else
    }This could be useful if you were to write a generic cache, for example.
    A similar thing is true for hashCode(), if you want to manage things in a HashSet, you'll need them to implement hashCode().
    If Object didn't have those methods, then you'd have to write that code against a more specific interface/class and it wouldn't be so general any more.

  • Accessing view object class (impl) method from bean (or vice versa)

    Halo everyone, I am using JDeveloper 11.1.2.1.0
    I have a UsersViewImpl class with a method which refresh the user table like below.
    public void resetEmployeeSearch() {
    removeApplyViewCriteriaName("viewCriteria");
    executeQuery();
    and I have a UserBean class with a method which reset the search fields values like below.
    public void resetInput(ActionEvent actionEvent) {
    ........RichInputText = input ...
    input.setValue("");
    AdfFacesContext.getCurrentInstance().addPartialTarget(searchForm);
    I would like to implement it in such a way that, once I press a button, both methods will be called.
    I have tried to call from bean method using UsersViewImpl vs = new UsersViewImpl ..... which is wrong and wont work.
    I have read about doing something like ViewObject vo = am.findViewObject("DeptView1") but I duno how to use it because I cant have a proper example.
    Any suggestion on accessing view object class (impl) method from bean (or vice versa)?
    Or is there any way to combine both method in the same class ?
    Thank you :(

    User, if you get class not found exceptions you need to tell us which classes you can't find. The JSFUtils and ADFUtils classes needing some other libraries which should already be part of your Fusion Web Application template (which your adf application should be based on). If you did not use this application template, you may have to add some libraries yourself.
    What is the diff of using the ADFUtils and OperationBinding way?
    The ADFUtils can get you access to the application module which you then use to call exposed methods on. The disadvantage of doing this is that you have to implement your own exception framework which then handles exceptions thrown by the application module. An other thing is that if you e.g. alter a VO which you use on the page this changes are not seen on the page until you refresh the page. The binding layer does not know about these changes so the iterators (which are used on the page to show the data) are not refreshed and so you don't see the changes.
    In general you should avoid using the application modul in a managed bean method and always use the binding layer (OperationBinding) to call methods. This ensures that exceptions are all handled the same way and that changes to the data model are reflected in the GUI.
    Timo

  • Native method in object class........

    I would like to know that which method of object class is a native method..........

    flounder wrote:
    The natives are getting restless.
    What they do with him when he arrives, I don't know.This reminds me of one of my favorite entries in Ambrose Bierce's [Devil's Dictionary|http://en.wikipedia.org/wiki/Devil%27s_dictionary]
    h3. Aborigines
    Persons of little worth found cumbering the soil of a newly discovered country. They soon cease to cumber; they fertilize.

  • Best practice for method calling on objects within a collection.

    Hi guys
    As you may be aware, based on my other thread here. I'm designing a card game in Java. I was hoping for some advice on the best practise on how methods should be called on a custom Object contained within a custom Collection.
    I have an instance variable for the Deck class as follows: List<Card> deckWhen creating an instance of the class I use deck = new ArrayList<Card>();So I have a Deck which only holds Card objects. My question is, for the Card methods, should I call them on the Card objects after 'getting' the Cards from the Deck or should I write methods within the Deck class which handles this method calling. Code explanation is as follows:
    Deck standardDeck = new Deck();I want to retrieve the suit value of a card within the deck. Is this the best way to do it this way:
    standardDeck.getCardAt(50).getSuit();
    //getCardAt is a method within the Deck class, getSuit() is a method within the Card classor this way:
    standardDeck.getSuitForCardAt(50);
    //getSuitForCardAt() is a method within the Deck class. This method calls the getSuit() method within its method body.Cheers for any help guys.
    Edited by: Faz_86 on Jul 10, 2010 9:53 AM

    Hey Saish
    Thanks for the response.
    My Card class does indeed override hashCode(), equals() and toString().
    The reason I am asking a card from the deck for its Suit is simply because of the rules of the game being played. The game I made is a 'Card Shredding' game where a player attempts to remove as many cards from their hand during each turn. The first to remove all their cards is the winner.
    When the game starts, two decks are created. A standard 52 card deck and an empty deck. Then 8 cards are dealt to each player and one card is dealt into the empty deck. The suit and value of the card on the empty deck called the 'shredding deck' dictates which moves are valid during each turn; The played card must match the Suit or the Value of the current card on the 'shredding deck'
    For example:
    Card on the empty deck = 8 of Spades
    The only card from a players hand which can be removed are any Spade or an Eight of any suit.
    Going back to the Deck.getSuitOfCardAtIndex(int index) , this method is needed because both the AI player and human player need to have the ability to take a look at the cards which have been added to the 'shredding deck'. Again this is because of the rules of the game. Therefore I need a method to take a look at the Suit and Value for any card in the 'shredding deck'.
    Taking all this into account, so far I have the following in my Deck class. Please comment on my design so far. As you can see I've tried to follow the Law Of Demter by creating many little wrapper methods. I understand totally wh getters and setters are bad but I cannot come up with a design solution to achieve what I need to based on the rules of the game without users getters. - Any tips on this would be great.
         public Card dealCard()
              Card cardToDeal = deck.remove(0);
              return cardToDeal;
         public void addCard(Card usedCard) //This method is used to add 'used' cards to the deck.
              deck.add(usedCard);
         public Card getFaceCard() //Returns the current face up playing card
              Card faceCard = deck.get(deck.size()-1);
              return faceCard;
         public int getFaceCardValue()
              int faceCardValue = deck.get(deck.size()-1).getValue();
              return faceCardValue;
         public int getFaceCardSuit()
              int faceCardSuit = deck.get(deck.size()-1).getSuit();
              return faceCardSuit;
         public String getFaceCardName()
              String faceCardName = deck.get(deck.size()-1).toString();
              return faceCardName;
         public Card getCardAt(int position) //Returns the current face up playing card
              Card card = deck.get(position);
              return card;
         public int getFaceCardValueAt(int position)
              int cardValue = deck.get(position).getValue();
              return cardValue;
         public int getFaceCardSuitAt(int position)
              int cardSuit = deck.get(position).getSuit();
              return cardSuit;
         public String getFaceCardNameAt(int position)
              String cardName = deck.get(position).toString();
              return cardName;
         public int getDeckSize() //When recycling cards, the size of the deck is needed to determine the best time to add more cards.
              return deck.size();
         }

  • Interrupting a Thread in a Remote Object?

    HI,
    I am trying to get some thread synchronization to happen between a client and a remote RMI object. Essentially what I am trying to accomplish, is that if I interrupt a call on a blocking method in the remote object, I want the thread to throw the InterruptException. For example, the following code represents what I am trying to accomplish:
    package bca.test.rmi;
    import java.rmi.Naming;
    import java.rmi.Remote;
    import java.rmi.RemoteException;
    import java.rmi.server.UnicastRemoteObject;
    public class InterruptThreadApp {
    RemoteBlockingObjectInt remote = null;
    public static void main(String[] args) throws Exception {
    //Create the remote object
    RemoteBlockingObject obj = new RemoteBlockingObject();
    //bind it to the registry
    Naming.rebind("rmi://localhost/blocking", obj);
    //start the client, or the thread which will access the blocking call remotely
    InterruptThreadApp app = new InterruptThreadApp();
    Thread blocking = null;
    //wait for the thread to start
    synchronized ( app ) {
    blocking = app.startClient();
    app.wait();
    Thread.sleep(2000);
    //now interrupt the thread (note: the remote object should be blocking in
    //the blockingMethod().. this should produce an InterruptException?
    blocking.interrupt();
    public Thread startClient() {
    Thread t = new Thread("Client") {
    public void run() {
    try {
    //get a handle to the stub
    remote = (RemoteBlockingObjectInt) Naming.lookup("rmi://localhost/blocking");
    //now make a call to the blocking method, but first wake up the client
    synchronized ( InterruptThreadApp.this ) {
    InterruptThreadApp.this.notify();
    //now make the blocking call
    remote.blockingMethod();
    catch (InterruptedException e) {
    System.out.println("WooHoo! This is what we want! But it never gets thrown :(");
    catch (Exception e) {
    e.printStackTrace();
    t.start();
    return t;
    package bca.test.rmi;
    import java.rmi.server.UnicastRemoteObject;
    import java.rmi.RemoteException;
    import java.rmi.Remote;
    public class RemoteBlockingObject extends UnicastRemoteObject implements RemoteBlockingObjectInt {
    Object obj = new Object();
    public RemoteBlockingObject() throws RemoteException {
    super();
    public void blockingMethod() throws RemoteException, InterruptedException {
    synchronized (obj) {
    System.out.println("About to block.. so we can be interrupted later");
    obj.wait();
    interface RemoteBlockingObjectInt extends Remote {
    public void blockingMethod() throws RemoteException, InterruptedException;
    When I make a call to "remote.blockingMethod()", it blocks in the remote object (buy just "wait" ing). I want to interrupt this thread, by issuing an Thread.interrupt(). When I do so (I call "blocking.interrupt()"), nothing happens... no exception is thrown.. it just silently fails.
    Ok, so I suppose that we can not interrupt a remote thread.. that is fine. But what if I want to interrupt the RMI thread making the remote call? I don't want it to block forever. How can I "cancel" the remote call?
    Ideally, I would like the remote.blockingMethod() call to throw an InterruptException when I issue an "interrupt()" on the blocking thread. Any suggestions on how I might accomplish this?
    Thanks,
    Bryan

    While you can interrupt the RMI call, you cannot stop the active processing. That is, you cannot force a thread to stop (see the Java API documentation on Thread.stop().)
    Since the Client RMI call is a waiting thread, you need another Client thread to do a secondary RMI call. The trick is to have the new RMI endpoint connection thread on the RMI Server interrupt the original RMI endpoint connection thread.
    The only way you can interrupt an RMI call is to have the endpoint connection thread that runs on the RMI Server be aware that the user may wish to interrupt it.
    The best means of interruption is for the endpoint connection thread to use "worker threads". The endpoint connection thread waits for the workers to finish and is interruptible by both the workers and other endpoint connection threads.
    Another means of interruption is for the endpoint connection thread to segment the task into units of work and check for an interruption between those units of work.
    There are two ways I've done RMI call interruption.
    One is for the Client to pass a unique id (UID -- that uniquely identifies the request) to the Server with the original call. When the Client wishes to interrupt the original call, using the separate thread, it does a new RMI call to the Server passing the UID.
    The new endpoint connection thread, using the UID, interrupts the original endpoint connection thread.
    The major problem with this is the unique id. It absolutely, positively must be unique. Otherwise you run the risk of Client_A purging Client_B's request.
    The second method requires callback. If your Client is behind a firewall then RMI callback is near impossible. In such a case you must come up with a way for the Server to call the Client that is secure (the firewall problem.)
    The Client must export a remote object and pass that remote object to the Server with the original call.
    The endpoint connection thread recognizes the remote object and does a call back to the Client passing information that uniquely identifies itself (UID). Since the Server generates the UID, it can guarantee uniqueness.
    The Client callback implementation runs as a separate thread since the Client is in fact an RMI Server itself (when it did the export.) The Client must save the UID. The Client must start a new thread for the interrupt procedure or inform a waiting thread that the Server called back.
    Just like method one, above, when the Client wishes to interrupt the original call, using the separate thread, it does a new RMI call to the Server passing the UID.
    The new endpoint connection thread, using the UID, interrupts the original endpoint connection thread. Simple.
    For an academic example using call back go over to Jini.org. They have an example called "Cancellation" at:
    http://starterkit-examples.jini.org/
    For a professional, open source implementation of both these methods go over to CoopSoft.com. The Tymeac (Java) projects support canceling both waiting and autonomous requests at:
    http://www.coopsoft.com/JavaProduct.html

Maybe you are looking for

  • Safari Crashes and then will not open yahoo.mail or gmail

    Safari Crashes and then will not open yahoo.mail or gmaill Is anyone else having these, or similar problems. i cannot log-in to my yahoo.com or onto gmail. The issue started yesterday. The message states that it cannot secure the connection. Any sugg

  • How to add special characters to field?

    As per topic... Virtual Office | Servcorp http://www.servcorp.com.au/ http://www.servcorp.net/

  • Problems Connecting to VPN Server ( Mac OS X Server 10.6.2

    Hi We are using Mac OS X Server 10.6.2 ( Snow Leopard Server). I have set it up as a VPN server. When I connect to it from my Macbook Pro ( Snow Leopard ), the logs in Server Admin shows, 2010-01-05 10:45:35 SGT Incoming call... Address given to clie

  • ITunes 12: Changing my genres, fixes don't stick

    Just downgraded to iTunes 12 since Apple's answer to the MS Paper Clip, the little dialog window that won't die, finally got the best of me. What a mistake. Please don't do it, peeps. My main annoyance is that the genres of my music keep changing. I

  • Change the MacAir with MacbookPro

    I have the macbook air 128 G 11inches...it is new and with out any problem. can I change it with Macbook pro 13inches? if yes how can i do that? and what is the conditions?