Thread -- notify()

i m declaring wait() function in one of my synchronized code n know i need to notify () this wait function from other class which gives me error saying
"IllegalMonitorStateException : current thread not owner" even though i have used synchronized method
plz help me to call notify function from some other class

The notifing thread must own the motinor of the very object it wants to notify. If you are sync'ing on someting else, it won't work.

Similar Messages

  • A Thread Notifying Another Thread

    Here is what I would like to accomplish. Before thread A terminates, I would like thread A to notify thread B that it is about to terminate. I would like to do this notification through a function, which need to be called regardless if the thread terminates gracefully.
    Is there a way to define this function and have the JVM call it. I was told by someone that JVM calls a function when a thread exits and I can override the function so that thread A notifies thread B. If this function exists, please let me know how to accomplish this. If this function does not exist, what are my options, if any, to come up with a solution to this problem?
    thanks,
    Paul0al

    If you want to handle abnormal termination due to an uncaught exception, (OutOfMemoryError, NullPointerException, etc.) you can put thread A into a subclass of ThreadGroup, which you subclass like this:
    // Untested code! Coding on the fly...
    class MyThreadGroup extends ThreadGroup {
      public void uncaughtException(Thread t, Throwable e) {
        // Notify your other thread here of the death of our thread
    }So our thread group's uncaughtException() method is called when a thread in it dies. I believe this is the only useful feature of ThreadGroup, although I think inheriting ClassLoaders might be a feature only provided by ThreadGroup as well.

  • Thread management in servlet

    Here is the problem that i am trying to solve - and get better understanding of issues to look out for.
    1) Problem to solve
    Clients sends an http request to an distributor server. The request contains a list of tasks. Each such task can be sent to a particular handling server (out of a known set) which can handle the request. Each task has a task type, which identifies which server the request needs to be passed to. The responses from the handler servers are then to be collected and passed back the client as a consolidated response.
    On the distributor server, the servlet thread that is handling the request will
    a. need to spread the requests for various handling servers
    b. send the requests in parallel to handling servers
    b. get all the responses , consolidate and send back
    2)Proposed solution
    I was thinking of having a thread pool - one thread for each handling server, initialized within servlet . When the distributor server receives a request - the tasks would be spread to these handling threads. The distributor thread would then wait, until the handling threads notify.
    When a notification is received - the distributor thread will need to check if all responses are received. If not - it would need to wait (till a max_timeout) else return the response to client
    3)Questions
    - This involves waiting on the thread created by serlvet container (the distributor thread) and creating a threadpool. Thread creation and management by application in web-container is generally dissuaded - but given this issue - i see no other alternative
    suggestions ? Its been a long email - thanks for considering
    Fred

    How many clients for the entry server do you presume for the application ? I ask this because it is very possible that the server to remain without available threads and give errors. If you use different servers for the final requests I suppose that are some very time consuming processes. What kind of application are running on these servers so that you want to use this kind of distributed computing ?
    Why did you choose as an entry point a servlet container and http request for this kind of problem ? Do you need a graphic response in the browser ? If the response time is too long, the browser (Internet Explorer) will show exception and will not wait for the response (for this you must set some variabiles on client). Also the J2EE server must be set so that not to throw a time-out exception.
    To prevent these, you could do so that not to block the distributor thread and let it send the answer back to the client. Then you can tell to client browser to query the server from time to time to check the status of the execution (you can do that from javascript). When the execution is ready you can retrun the response to the client. Doing this way you will not block the application server threads.
    Now in the back end, you must somehow to take some identificators from the processes and sent them back to the client.
    You can use a database to make the bridge between the central server and the other processes (here you can put the processes identificators). When the processes end up they update their results in the database.
    The client, when will make the repetitive requests, will check the status of the processes in the database with given identificators.
    Sounds like an interesting project.

  • Threads does not work correctly

    The follow program working with threads. We have two classses : Producer and Customer which working with the same object (which type is class Q). Producer produces data. Customer should capture the data. The Q class must be synchronized. But code does not work (compile under NetBeans 6.0)
    class Q {
    int number = 0;
    boolean filled = false;
    void put (int n) {
    while (filled){
    try {
    wait();
    catch(InterruptedException e) {
    System.out.println("Interrupted");
    number = n;
    System.out.println("Put : " + number);
    filled = true;
    notify();
    void get () {
    while (!filled) {
    try {
    wait();
    catch(InterruptedException e) {
    System.out.println("Interrupted");
    System.out.println("Got : " + number);
    filled = false;
    notify();
    class Producer implements Runnable {
    Q obj_link;
    Thread t;
    Producer (Q obj_link) {
    this.obj_link = obj_link;
    t = new Thread(this, "Producer");
    t.start();
    public void run () {
    int i = 0;
    while (true) {           
    obj_link.put(i++);
    class Customer implements Runnable {
    Q obj_link;
    Thread t;
    Customer (Q obj_link) {
    this.obj_link = obj_link;
    t = new Thread(this, "Customer");
    t.start();
    public void run () {
    while (true) {
    obj_link.get();
    public class Main {
    public static void main(String[] args) {
    Q common_obj = new Q();
    Producer pr = new Producer (common_obj);
    Customer cs = new Customer (common_obj);
    try{
    pr.t.join();
    cs.t.join();
    catch(InterruptedException e) {
    System.out.println("Interrupted");
    System.out.println("Program Over");
    }

    The follow program working with threads. We have two classses : Producer and Customer which working with the same object (which type is class Q). Producer produces data. Customer should capture the data. The Q class must be synchronized. But code does not work (compile under NetBeans 6.0).
    I.e. i am waiting for the follow result:
    1. pr thread starts with common_obj object
    2. cs thread starts with common_obj object
    3. pr thread tries call common_obj.put(i++) in infinite cycle:
    3.1 these lines does not work because filled now is set to false
            while (filled){
                try {
                    wait();
                catch(InterruptedException e) {
                    System.out.println("Interrupted");       
            }3.2 the follow code will be implemented:
            number = n;    // put value to number
            System.out.println("Put : " + number); // output result to console
            filled = true; // value was put. It can be got.
            notify(); // notify another thread (cs) that it should not waiting anymore.4. pr thread tries call common_obj.get() in infinite cycle:
    4.1 the following code will not be implemented anymore:
            while (!filled) {
                try {
                    wait();
                catch(InterruptedException e) {
                    System.out.println("Interrupted");       
            } since another thread notify current.
    4.2 the follow code will be implemented:
            System.out.println("Got : " + number);
            filled = false;
            notify();So the result of running this program should be:
    Put : 0
    Got: 0
    Put : 1
    Got: 1
    Put : 2
    Got: 2
    Put : 3
    Got: 3
    Put : 4
    Got: 4
    class Q {
        int number = 0;
        boolean filled = false;
        void put (int n) {
            while (filled){
                try {
                    wait();
                catch(InterruptedException e) {
                    System.out.println("Interrupted");       
            number = n;
            System.out.println("Put : " + number);
            filled = true;
            notify();
        void get () {
            while (!filled) {
                try {
                    wait();
                catch(InterruptedException e) {
                    System.out.println("Interrupted");       
            System.out.println("Got : " + number);
            filled = false;
            notify();
    class Producer implements Runnable {
        Q obj_link;
        Thread t;
        Producer (Q obj_link) {
           this.obj_link = obj_link;
           t = new Thread(this, "Producer");     
           t.start();
        public void run () {
            int i = 0;
            while (true) {           
                obj_link.put(i++);
    class Customer implements Runnable {
        Q obj_link;
        Thread t;
        Customer (Q obj_link) {
           this.obj_link = obj_link;
           t = new Thread(this, "Customer");     
           t.start();
        public void run () {
            while (true) {
                obj_link.get();
    public class Main {
        public static void main(String[] args) {
            Q common_obj = new Q();
            Producer pr = new Producer (common_obj);
            Customer cs = new Customer (common_obj);
            try{
                pr.t.join();
                cs.t.join();
            catch(InterruptedException e) {
                System.out.println("Interrupted");
            System.out.println("Program Over");
    }the follow result of implementation I found:
    run:
    Put : 0
    Exception in thread "Producer" java.lang.IllegalMonitorStateException
    Got : 0
    at java.lang.Object.notify(Native Method)
    at threadstudy2.Q.put(Main.java:19)
    Program Over
    at threadstudy2.Producer.run(Main.java:50)
    at java.lang.Thread.run(Thread.java:619)
    Exception in thread "Customer" java.lang.IllegalMonitorStateException
    at java.lang.Object.notify(Native Method)
    at threadstudy2.Q.get(Main.java:33)
    at threadstudy2.Customer.run(Main.java:68)
    at java.lang.Thread.run(Thread.java:619)
    BUILD SUCCESSFUL (total time: 1 second)

  • Running another thread not to block UI

    I do some heavy operation inside the actionPerformed (load images from File Chooser, resize it for display and populate it in the ScrollPane etc) and I realize that the windows freezes until the whole operation is finished. And it doesn't really help that I do repaint() or validate(). I make some research and some of the books and people from forums say that I actually needed to dispatch another thread to run the heavy operation. So that I won't block the UI interface and can update things accordingly. But the problem is, I don't have any clear example to understand this concept. How to clean up the thread after operation finished. How can a thread notify the progress back and etc. I need to know how much images has been loaded so that I can update the progress bar and so on. Can anyone help me point out a good example? :D

    Think I should show my code snippet to you
    public void actionPerformed(ActionEvent e) {
            if (e.getSource() == BtnBrowse) {
                int returnVal = fcSelectFile.showDialog(this,"Select");
                if (returnVal == JFileChooser.APPROVE_OPTION) {
                    file= fcSelectFile.getSelectedFiles();
                    //This is where a real application would open the file.
                    Thread worker=new Thread(){
                            public void run(){
                                int count=0;
                                selectedFile=new JLabel[file.length]; 
                                while(count<file.length)
                                {   final int index=count;
                                    String actualFile=file[count].toString();
                                    String fileName= file[count].getName();
                                    selectedFile[count]=new JLabel(createImageIcon(actualFile,fileName));
                                    SwingUtilities.invokeLater(new Runnable(){
                                    public void run(){
                                    PnlImageHolder.add(selectedFile[index]);
                                    PnlImageHolder.repaint();
                                    PnlImageHolder.validate();
                                    count++;
                    worker.start();
                    ScpImageScroller.getViewport().add(PnlImageHolder);
    }

  • How to notify() the main method in the given code snippet

    consider the given code snippet
    code
    public class WaitTest {
    public static void main(String [] args) {
    System.out.print("1 ") ;
    synchronized(args) {
    System.out.print("2 " ) ;
    try {
    args.wait();
    catch(InterruptedException e){}
    System.out.print("3 ");
    code
    Here since there are no threads to notify the main()method the statement System.out.print("3 "); never gets executed.And i cannot use the non static notify() from a static context.In this case how will I notify the main() method.

    A thread can only do one thing at a time.
    It cannot be waiting and notifying at the same time.
    notify only works if another thread is waiting.
    wait() only stops if another thread notify/notifyAll() it at the same time.

  • Notify/Wait or Observable/Observer?

    Hi,
    I have one thread process the data and store the result in a data object. Several threads access the data object to display.
    Which one to use:
    1) Have the processing thread notify the display threads when it's done? Using thread wait()/notify()?
    2) Have the data object be the observable, and the dislay threads be the observers? Using the observable/observer concept?
    Thanks

    How exactly would you code the wait/notify method calls? I had dynamic data that was used to update the data models for a JList and a JTable, and found it difficult to notify the models correctly, after the data changed.
    Somehow the object has to "post" the fact that it has changed, a job for Observer/Observable. The Thread tutorial and the various Swing tutorials don't quite describe this in a way I understand. Can somebody give an example of how to use notify/wait in this sort of situation? Thanks.

  • Waking up a thread from ActionListener

    I have a Swing GUI that uses a separate class for handling the user actions(implements ActionListener).
    When the user clicks a button in the GUI a new thread is started that connects to a server and after sometime goes to wait().
    Now, when the user clicks on another button, i want the thread (which is in wait() mode) to wakeup and continue.
    In order for the client thread to go to wait() mode() i use the code below:
       private synchronized void authenticatedClient()
            System.out.println("authenticateClient started");
            boolean wait = true;
            while(wait)
                try
                    this.wait();
                catch (InterruptedException interException)
                    System.out.println("Thread wait() was interrupted!!");
                System.out.println("Woke up: pass command to server and sleep again");
                // get the command that user asked for.
                // write the command to the server
                writeData("TAKE_MY_COMMAND");
        } In the same client thread i have another method that will be used to notify() the clientAuthenticated():
        private synchronized void wakeUp()
            System.out.println("wakeUp() was called");
            try
                this.notify();
            catch (IllegalMonitorStateException illegal)
                System.out.println("Thrown to indicate that a thread has attempted to wait on " +
                          "an object's monitor or to notify other threads waiting on an object's " +
                          "monitor without owning the specified monitor.");
        }My problem is how can i call the wakeUp() from the class that implements the ActionListener.
    Any help will be greatly appreciated.

    Hi, i think i have found the root of my problem but if someone can help me i will appreciate it much.
    The ActiionListener class has two constructors. One constructor is used for the main GUI and the second constructor is used for tthe connect dialog.
    When the application starts, the main GUI is using the first constructror. The user presses the button Connect, and the Dialog window opens. This window though is using the second constructor in the ActionListener class to listen for the connect command. Now when the user completes the dialog and presses connect,, a new thread starts which takes the class Networking as an argument.
    After the networking thread does what is supposed to do it waits (blocked).
    Now the user presses the button Continue on the main GUI which uses the first constructor.
    The Continue buton is supposed to notify() the blocked thread but AS I believe it cant because the actual thread was created using the second constructor.
    So i need either a way to make both the main GUI and the Dialog listen on the same instance of the ActionListener so i can refer to the thread,,,,, OR someone to help me understand what is wrong.
    Below is the code from my ActionListener class:
    public class EventHandling implements ActionListener
        private HAClientFrame clientFrame = null;  
        private ConnectDialog connectDialog = null;
        private Thread thread;
        private NetworkingThread netThread;
         * constructor
         * @param haClientFrame
        public EventHandling(HAClientFrame haClientFrame)
            this.clientFrame = haClientFrame;
         * constructor
         * @param connectDialog
        public EventHandling(ConnectDialog connDialog)
            this.connectDialog = connDialog;
         * Process the events
        public void actionPerformed(ActionEvent e)
    // connect
    // THE CODE BELOW IS EXECUTED HAVING USED THE SECONDCONSTRUCTOR
            if (e.getActionCommand().equals("ConnectDialog"))
                if (validateInput())
                    connectDialog.setVisible(false);
                    netThread = new NetworkingThread(connectDialog.getAddress(),
                            connectDialog.getPort(), connectDialog.getUsername(),
                            connectDialog.getPassword());
                    thread = new Thread(netThread);
                    thread.start();
                    connectDialog.setFieldsNull();
                    connectDialog.dispose();
                    username = null;
                    password = null;
                else
                    JOptionPane.showMessageDialog(null,
                            "One or more fields are wrong.Please try again.",
                            "Error on input fields", JOptionPane.ERROR_MESSAGE);
    // THE CODE BELOW IS EXECUTED HAVING USED THE FIRST CONSTRUCTOR
    else if (e.getActionCommand().equals("LOCK"))
                System.out.println("LOCK command at eventhandling");
    // THIS SHOULD WORK BUT IT DOESNT
    thread.notify();
    }The code of the dialog box: (not all just the important bits):
    public class ConnectDialog extends JDialog
    private EventHandling handler = new EventHandling(this);
    jButton.addActionListener(handler);
    The code is working but its much to show all here. This is just how i listen for a button to get pressed.
    How could i make two classes listen from the same instance of the EventHandling class??I believe this will solve my problem.
    Any other help greatly appreciated
    Thanks again

  • Working with threads

    hello all.
    I find some program that will help me in my work.
    but know i don't know how to change it that it will fit my project. i just want to work with thread pool. i find some code that can do this.
    mu problem is that i don't know how to change the task and the run functions in that program because they are interface. and when i do change them I get all the code errors.
    can you give me an example how can i change this code to do some, like that the task will print something or do something else.
    the code is:
    thanks alot!
    * To change this template, choose Tools | Templates
    * and open the template in the editor.
    package work2;
    import java.util.ArrayList;
    import java.util.List;
    * @author vitaly87
    public class ThreadPool {
    /** Simple thread pool. A task is executed by obtaining a thread from
    * the pool
      /** The thread pool contains instances of {@link ThreadPool.Task}.
      public interface Task {
        /** Performs the task.
         * @throws Throwable The task failed, and the worker thread won't be used again.
        void run() throws Throwable{}
        /** A task, which may be interrupted, if the pool is shutting down.
        public interface InterruptableTask extends Task {
            /** Interrupts the task.
             * @throws Throwable Shutting down the task failed.
            void shutdown() throws Throwable;
        private class Poolable {
            private boolean shuttingDown;
            private Task task;
            private Thread thread;
            Poolable(ThreadGroup pGroup, int pNum) {
                thread = new Thread(pGroup, pGroup.getName() + "-" + pNum){
                    public void run() {
                        while (!isShuttingDown()) {
                            final Task t = getTask();
                            if (t == null) {
                                try {
                                    synchronized (this) {
                                        if (!isShuttingDown()  &&  getTask() == null) {
                                            wait();
                                } catch (InterruptedException e) {
                                    // Do nothing
                            } else {
                                try {
                                    t.run();
                                    resetTask();
                                    repool(Poolable.this);
                                } catch (Throwable e) {
                                    discard(Poolable.this);
                                    resetTask();
                thread.start();
            synchronized void shutdown() {
                shuttingDown = true;
                final Task t = getTask();
                if (t != null  &&  t instanceof InterruptableTask) {
                    try {
                        ((InterruptableTask) t).shutdown();
                    } catch (Throwable th) {
                        // Ignore me
                task = null;
                synchronized (thread) {
                    thread.notify();
            private synchronized boolean isShuttingDown() { return shuttingDown; }
            String getName() { return thread.getName(); }
            private synchronized Task getTask() {
                return task;
            private synchronized void resetTask() {
                task = null;
            synchronized void start(Task pTask) {
                task = pTask;
                synchronized (thread) {
                    thread.notify();
      private final ThreadGroup threadGroup;
      private final int maxSize;
      private final List waitingThreads = new ArrayList();
      private final List runningThreads = new ArrayList();
      private final List waitingTasks = new ArrayList();
      private int num;
      /** Creates a new instance.
       * @param pMaxSize Maximum number of concurrent threads.
       * @param pName Thread group name.
      public ThreadPool(int pMaxSize, String pName) {
        maxSize = pMaxSize;
        threadGroup = new ThreadGroup(pName);
      synchronized void discard(Poolable pPoolable) {
        pPoolable.shutdown();
            runningThreads.remove(pPoolable);
            waitingThreads.remove(pPoolable);
      synchronized void repool(Poolable pPoolable) {
            if (runningThreads.remove(pPoolable)) {
                if (maxSize != 0  &&  runningThreads.size() + waitingThreads.size() >= maxSize) {
                    discard(pPoolable);
                } else {
                    waitingThreads.add(pPoolable);
                    if (waitingTasks.size() > 0) {
                        Task task = (Task) waitingTasks.remove(waitingTasks.size() - 1);
                        startTask(task);
            } else {
                discard(pPoolable);
      /** Starts a task immediately.
       * @param pTask The task being started.
       * @return True, if the task could be started immediately. False, if
       * the maxmimum number of concurrent tasks was exceeded. If so, you
       * might consider to use the {@link #addTask(ThreadPool.Task)} method instead.
      public synchronized boolean startTask(Task pTask) {
        if (maxSize != 0  &&  runningThreads.size() >= maxSize) {
          return false;
            Poolable poolable;
        if (waitingThreads.size() > 0) {
            poolable = (Poolable) waitingThreads.remove(waitingThreads.size()-1);
        } else {
                poolable = new Poolable(threadGroup, num++);
        runningThreads.add(poolable);
            poolable.start(pTask);
        return true;
      /** Adds a task for immediate or deferred execution.
       * @param pTask The task being added.
       * @return True, if the task was started immediately. False, if
       * the task will be executed later.
      public synchronized boolean addTask(Task pTask) {
        if (startTask(pTask)) {
          return true;
        waitingTasks.add(pTask);
        return false;
      /** Closes the pool.
      public synchronized void shutdown() {
            while (!waitingThreads.isEmpty()) {
                Poolable poolable = (Poolable) waitingThreads.remove(waitingThreads.size()-1);
                poolable.shutdown();
            while (!runningThreads.isEmpty()) {
                Poolable poolable = (Poolable) runningThreads.remove(runningThreads.size()-1);
                poolable.shutdown();
      /** Returns the maximum number of concurrent threads.
       * @return Maximum number of threads.
      public int getMaxThreads() { return maxSize; }
      /** Returns the number of threads, which have actually been created,
         * as opposed to the number of currently running threads.
        public synchronized int getNumThreads() { return num; }
    }

    Sounds like you should read up on the [java tutorials |http://java.sun.com/docs/books/tutorial/essential/concurrency/] on threading.
    I found some car parts that will help me drive. And no, I don't know how to put them together to make a car. But I want to drive on the highway! I found some car parts that can do this.

  • Notify & wait

    Here is a snip of my code :
    public void start()
       setVisible(true);
       long wait_time;
       for (int counter = 0; counter < 10; counter++)
          try
             wait = false;
             wait_time = (long) ((Math.random() * 15000)+5000);
             Thread.sleep(wait_time);
             t1.start_timer();
             // some code
             Thread.wait();
             t1.stop_timer();
          catch (InterruptedException e)      {}
    public void wait_finished()
       Thread.notify();
    }When I run the wait_finished() method I get "non-static method wait() cannot be referenced from a static context" error message. Any ideas what Im doing wrong ?

    You can only call wait on an object if you own that objects lock.
    Try this.
    Thanks for your prompt reply jboozer.
    I change my code like you said, now it looks something
    like this :
    public void start()
    setVisible(true);
    long wait_time;
    for (int counter = 0; counter < 10; counter++)
    try
    wait = false;
    wait_time = (long) ((Math.random() *
    m() * 15000)+5000);
    Thread.sleep(wait_time);
    t1.start_timer();
    synchronized
    wait();
    // some code
    t1.stop_timer();
    catch (InterruptedException e)      {}
    public void wait_finished()
    synchronized
    notify();
    The above compiles ok, but when I run the code I get
    an error when try to execute wait();
    "java.lang.IllegalMonitorStateException : current
    thread not owner " - error message
    What does this mean ?
    Cheers for any help.

  • Full Thread Dump...Deadlock occured in the code

    The following code generates error saying the following description:
    ERROR Start:
    SIGBUS occured.
    Full thread dump:
    "main" (TID:0x66c9360, sys_thread_t:0x7ad4f10, taskId:0x7ae447c state:runnable name:tJmain, stack_base:0x7ae447c, stack_high:0x1080 stack_size:19696) prio=5
    "Finalizer thread" (TID:0x66c9390, sys_thread_t:0x7ad0538, taskId:0x7ad4590 state:condition variable pend name:Finalizer threa, stack_base:0x7ad4588, stack_high:0x144 stack_size:15624) prio=1
    "Thread-0" (TID:0x66dd778, sys_thread_t:0x6560460, taskId:0x65644b8 state:condition variable pend name:Thread-0, stack_base:0x65644b0, stack_high:0xb48 stack_size:15628) prio=5
    Page Fault
    Program Counter: 0x0013c6a3
    Status Register: 0x00010202
    Error Code: 0x00130000
    Task: 0x6551d20 "Thread-3"
    ERROR End
    This is the code..........
    public class abc{
         private boolean ready;
         public synchronized void toggle1() {
              ready = false;                     // de-block the other thread
              try {
              notify();                     // inform the other thread
              }catch(IllegalMonitorStateException e) {
              e.printStackTrace();
              while (!ready) {               // block until the other
                   try {                    // thread sets "ready" to
                        wait();               // "true".
                   } catch (InterruptedException e) {
                   System.out.println("Error from toggle1:InterruptedException");
                   e.printStackTrace();
                   catch(Throwable e)
                   System.out.println("Error from toggle1:Throwable");
                   e.printStackTrace();
         public synchronized void toggle0() {
              ready = true;                    // de-block the other thread
              notify();                    // inform the other thread
              while (ready) {                    // block until the other
                   try {                    // thread sets "ready" to
                        wait();               // "false".
                   } catch (InterruptedException e) {}
    Would you please put look into it and suggest a solution
    Thanks
    Message was edited by:
    Indranil.Sarkar

    Ah well if you're back on 1.2 then that's about as much error information as you will get.
    JDK 1.2 is way past end-of-life. There is nothing you can do here to fix this problem.
    Note: just because your application code was written for 1.2 doesn't mean it won't run on a later version of the VM. Try 1.3.1 if you don't want to jump up to 1.5 or 1.6 (but 1.3.1 will soon hit end-of-life too).
    Sorry.

  • Slightly confused about notify method

    Hi,
    I'm currently studying for the SCJP exam and have 2 questions about the thread notify call.
    (1) Is it possible when a thread owns an object lock, i.e. say in synchronized code, that it can call the notify method on a particular thread. For example, say there are 2 threads, names thread1 and thread2, and thead1 obtains object lock, can it call Thread2.notify()? The reason I'm read conflicting web-pages, saying it isn't possible for 1 thread to notify another thread and it is up to Object to decide which thread to invoke, say must use notifyAll() or notify() call. Is this true?
    (2) Which thread in following code is Thread.sleep() referring to? Is it the main thread that created 2 threads?
    class running extends Thread
         public void run(){
    public class fredFlintStone{     
         public static void main(String[] args) {
              running  thread1 = new running();
              running thread2 = new running();
              thread1.start();
              thread2.start();
              try
              //confused here     
            Thread.sleep(12L);
              catch(InterruptedException e)
    }Cheers!

    its best not to confuse terminology here.
    marktheman wrote:
    I ... have 2 questions about the thread notify call.Thread is an object which has a notify() method. However you should never use it. You should only use notify() on regular objects.
    (1) Is it possible when a thread owns an object lock, A Thread holds a lock, see [http://java.sun.com/javase/6/docs/api/java/lang/Thread.html#holdsLock(java.lang.Object)]
    i.e. say in synchronized code, that it can call the notify method on a particular thread. A thread calls notify() on an object not a given thread. (Unless that object is a thread, but don't do that!)
    For example, say there are 2 threads, names thread1 and thread2, and thead1 obtains object lock, can it call Thread2.notify()?It can, but it would fail as you can only call notify() on an object you hold the lock to.
    The reason I'm read conflicting web-pages, saying it isn't possible for 1 thread to notify another thread It is possible but not in any useful way.
    and it is up to Object to decide which thread to invoke,The Object has no say in the matter, its up to the scheduler in the OS.
    say must use notifyAll() or notify() call. Is this true?no.
    (2) Which thread in following code is Thread.sleep() referring to? The javadoc says "Causes the currently executing thread to sleep". You should always check the documentation for asking that sort of question.

  • BPM Exception handling for RFC errors

    Hi all
    I have to handle the exception which would be like below:
    com.sap.aii.af.ra.ms.api.DeliveryException: error while processing message to remote system:com.sap.aii.af.rfc.core.client.RfcClientException: could not get a client from JCO.Pool: com.sap.mw.jco.JCO$Exception: (102) RFC_ERROR_COMMUNICATION: Connect to SAP gateway failed
    I am trying to put Block step and things are not working fine. Can anyone please explain me the steps to trap the exception?
    My scenario has synchronous call to RFC FM.
    Rightnow i have inserted Exception branch in my Block step and put the send step to write the error file.  I have put the Synchronous SEND step as part of block. This is not working.
    Help please??

    Hello Samuel,
    Just to close this thread and finish up my own search, where I met your discussion, here I'm quoting two experts of this forum:
    "you cannot catch the exception's value in the XI "
    (see posting from Michal Krawczyk, Jun 12, 2006, in thread catch the exception)
    "The content of a fault message are not accessible inside a BPM."
    (see posting from Bhavesh Kantilal, Oct 3, 2007, in thread Notify user about Exception in BPM)
    Regards,
    Dennis

  • Event-driven Socket Programming

    I've developed an application that communicates with a device over TCP/IP. Right now I have an infinite loop in another thread that continually checks for data on the socket, calling Thread.sleep() each time to prevent the receive thread from using the entire CPU, but I think this may be limiting my throughput. I'd like to either find a class that will generate an event for me when data arrives (which I'm doing myself at present), or be able to call wait() and have my thread notify()ed when data arrives on the socket. Can either of these things be done?

    I see. Could you post some of your code please? I
    suspect you are doing a number of things incorrectly
    here. Thread.sleep is not a good sign. I suspect you
    may be using available.Yes, I'm using .available(). In the code below, link is a wrapper around a TCP socket. Incoming messages are delineated by a start and end byte, and the parseByte() function switches states and resets the receiveOffset counter depending on each incoming byte. Fully blocking I/O was not an option, as I needed to be able to detect incomplete messages and deliver an event to the application.
                       /* Continue running until the port is closed and there is no data left */
                       while(link != null && (link.isOpen() || receiveOffset > 0)) {
                               /* Read all available bytes and parse them one at a time */
                               while(link.available() > 0) {
                                       byte b;
                                       /* Parse the next input byte */
                                       b = link.read(1)[0];
                                       parseByte(b);
                                       /* Reset the no-input loop counter as there was input */
                                       loopCount = 0;
                               /* Increment the no-input loop counter if there is data in the receive buffer */
                               if(receiveOffset > 0) {
                                       loopCount++;
                               } else {
                                       /* Reset the no-input loop counter as the receive buffer is empty */
                                       loopCount = 0;
                               /* Check for too many loops with data in the receive buffer */
                               if(loopCount > LOOP_MAX) {
                                       /* Incomplete message - code omitted */
                               /* Allow other threads to run */
                               try { Thread.sleep(1); } catch(Exception e) { }
                       }

  • Exception handling in integration processes

    Hi,
    I have a very simple question but I can't find an answer. I have designed an integration process that upon several other things send synchroneously a message to an ABAP proxy. Sometime the ABAP proxy generates exception. In my integration process these exceptionx are catched in a specific branch.
    My question is: how to access the data contained in the catched exception (message, text....)?
    Regards,
    Yann Le Blevec

    Hello Yann,
    There is no solution for your problem, I guess. I didn’t try it on my own, but in my own research on sdn I found two experts positions to that issue:
    "you cannot catch the exception's value in the XI "
    (see posting from Michal Krawczyk, Jun 12, 2006, in thread catch the exception)
    "The content of a fault message are not accessible inside a BPM."
    (see posting from Bhavesh Kantilal, Oct 3, 2007, in thread Notify user about Exception in BPM)
    Regards,
    Dennis

Maybe you are looking for

  • How to change condition type of Markdown price?

    Dear Expert, When I active markdown price, the system create price with condition type VKP0 (same as article regular retail price). Now I want system create price with other condition type, for example ZXXX. Could you give any help or tips? Thank you

  • Session variable and script error

    Hello; I am still writting this script that turns a bg sound on and aff for the whole site to remember. I have a good start on this code, but I am running into issues. 1. I am trying to use a checkbox to make the selection, and when it is clicked, it

  • Tried to restart apple tv. Now it is frozen on the apple

    My apple TV has been running poorly. Attempted to update software but it was unsuccessful. Attempted to restart and now it is frozen on the apple screen.  Help

  • IDVD question from a total newcomer

    Hi folks, I have a Mac G4 that I bought second hand. It does NOT have iDVD on it, and I want to buy it. Does iLife 06 provide the software or is it just an upgrade? I ask this because on the description it reads... "iLife '06, the must-have update to

  • Export is very slow

    Hi, We have created a new database. The db version is 9.2.0.4 It is available on Sun Solaris V890 and OS is Solaris 9. In general the performance is very good, but ONLY export is taking too much time. setting direct and buffer parameters didn't help.