RMI and Threads: Calling wait() on a remote object

I created a counter as a remote object.
Multiple clients are displaying the counter value.
If one of the clients increments the counter, I want the displayed counter value on every client to be updated to the new value (of the counter on the server).
Therefore every client starts a new thread to "listen" for changes of the countervalue. I wanted to call the wait() method on the remote object (the remote counter). But i think it will be called on the stub instead of on the actual remote object.
Therefore i created a extra method waitForChange() on the remote object.
public void waitForChange() throws RemoteException, InterruptedException {
     synchronized(this) {
          wait();
This method only calls the wait() method. Now I'm sure it's called on the remote object and not on the stub.
This works, but my question is: is there a better way to do this?
Code:
==========================================
The remote interface
==========================================
import java.rmi.Remote;
import java.rmi.RemoteException;
public interface RemoteCounter extends Remote {
     void incrementCounter() throws RemoteException;
     int getCounterValue() throws RemoteException;
     void waitForChange() throws RemoteException, InterruptedException;
} ==========================================
The implementation of the remote interface
==========================================
import java.rmi.*;
import java.rmi.activation.*;
import RemoteCounter;
public class RemoteCounterImpl extends Activatable
     implements RemoteCounter {
     private static final long serialVersionUID = 1L;
     private int counter = 0;
     protected RemoteCounterImpl(ActivationID id, MarshalledObject data) throws RemoteException {
          super(id, 0);
     public void incrementCounter() throws RemoteException {
          synchronized(this) {
               counter++;
               notifyAll(); //Inform all clients of the new countervalue;
     public void waitForChange() throws RemoteException, InterruptedException {
          synchronized(this) {
               wait();
     public int getCounterValue() throws RemoteException {
          return counter;
}==========================================
A piece of code registering the remote object
==========================================
ActivationDesc desc = new ActivationDesc(agi, "RemoteCounterImpl", codebase, data);
//Register with rmid
RemoteCounter counter = (RemoteCounter)Activatable.register(desc);
// Bind the stub to a name in the registry running on 1099
Naming.bind("Counter", counter);==========================================
The panel containing a button, a label
which starts a new thread listening for
counter value changes
==========================================
import javax.swing.*;
import java.awt.Dimension;
import java.awt.event.*;
import java.rmi.*;
import org.personal.exam.services.RemoteCounter;
public class PanelCounter extends JPanel {
     private static final long serialVersionUID = 1L;
     JLabel labelX = new JLabel("Press testbutton");
     Thread t;
     RemoteCounter remoteCounter;
     public PanelCounter()     {
          try {
               jbInit();
          } catch(Exception e) {
               e.printStackTrace();
     private void jbInit() throws Exception
          this.setLayout(new BoxLayout(this, BoxLayout.Y_AXIS));
          this.setPreferredSize(new Dimension(450,300));
          // The securityManager is required to make is possible
          // to download classes from the server
          if (System.getSecurityManager() == null) {
               System.setSecurityManager(new RMISecurityManager());
          //Create a testButton to increment the counter          
          JButton testButton = new JButton("Increment");
          testButton.addActionListener(new ActionListener(){
               public void actionPerformed(ActionEvent arg0) {
                    incrementCounter();
          this.add(testButton);
          //Add a label to display the counter value
          this.add(labelX);
          // Create thread to listen for counter value changes
          try {
               remoteCounter = (RemoteCounter)Naming.lookup("Counter");
               CounterValueChecker cvl = new CounterValueChecker(labelX, remoteCounter);
               //Start a thread to listen for changes of the countervalue
             t = new Thread(cvl);
             t.start();
          } catch(Exception e) {
               e.printStackTrace();
          this.setVisible(true);
     private void incrementCounter() {
          String message = "error";
          try {
               remoteCounter.incrementCounter();
               message = "Current value is " + remoteCounter.getCounterValue();
          } catch(Exception e) {
               System.out.println("Test Exception: " + e.getMessage());
               e.printStackTrace();
          labelX.setText(message);
}==========================================
The runnable implementation used by the
thread to wait for counterchanges
==========================================
import java.rmi.RemoteException;
import javax.swing.JLabel;
import org.apache.log4j.Logger;
import RemoteCounter;
public class CounterValueChecker implements Runnable {
     private JLabel counterLabel;
     private RemoteCounter remoteCounter;
     public boolean keepChecking= true;
     private Logger logger = Logger.getLogger(this.getClass());
     public CounterValueChecker(JLabel counterLabel, RemoteCounter remoteCounter){
          this.counterLabel = counterLabel;
          this.remoteCounter = remoteCounter;
     public void run() {
          while(keepChecking) {
               int newVal = -1;
               synchronized(remoteCounter) {
                    try {
                         //remoteCounter.wait();
//this does not work. I think because the wait() method is called on the
//stub instead of on the actual remote object
                         remoteCounter.waitForChange();
                    } catch (InterruptedException e) {
                         keepChecking = false;
                         break;
                    } catch (RemoteException re) {
                         re.printStackTrace();
                    try {
                         newVal = remoteCounter.getCounterValue();
                    } catch (RemoteException re) {
                         re.printStackTrace();
                    counterLabel.setText("New value: " + newVal);
}This is just a little test. Actually I want to notify clients of changes in data displayed in a Table. If one client saves one record of the data, i want the new record to be displayed immediatly on all clients that are viewing the same data.

I've been doing some reading about RMI and callback.
As I understand it, there's a remote object is running on the client now as wel. And the server makes a call to the client.
But now the server makes a call to one client.
And the point is, I want all clients to be updated with the new value.
Does this mean, I have to keep a list with references to all clients connected to the server?
I my code the notifyAll() method causes all waiting Threads (running on several clients) to wake up and do something (getting the new counter value).

Similar Messages

  • I have iPhone 5 iOS 7.0.2 and my call waiting stopped working. Anyone know how to fix this ? Or also having this issue? I hear the beep when the call comes in but not ID and no option to switch calls.

    My call waiting stopped working in iPhone 5 iOS 7.0.2 ? Anyone have this issue or know how to fix it?

    I have this issue as well and it really bothers me.

  • Airport extreme base station and internet call waiting/caller ID

    I have dial up connection through Earthlink that includes the internet call waiting feature (a pop up window when I'm online showing an incoming call and the caller ID). It only works when I am dialed in directly through the modem on my computer but does not work while I am connected with the wireless base station. I am wondering if there is a way to use or set-up this feature so that the pop up window showing an incoming call works when connected through the wireless base station.

    Duanne-
    Thanks very much-I appreciate your quick response. Maybe someday the area I live will graduate to high speed and I won't have to suffer dial-up!
    Smurf-

  • Help Please!!!!!  RMI and Threads

    My server has 10 threads doing constant polling of network equipment through use of SNMP. I have a servlet that connects to my server and retrieves collected information by using RMI and displays it in the browser window. Browser refreshes the information very often. So, there is a constant flow of RMI traffic between the server and the servlet.
    Here is the problem:
    There are times when my server stops responding to RMI requests issued by the servlet. All 10 threads that are doing SNMP polling stop being scheduled by the JVM. They block! This picular situation occurs with the server only during RMI requests coming from servlet. It doesn't always happen though. Also, I've noticed that if RMI load is high this problem emerges again.
    I get no RMI exceptions.
    I am using Apache and Jserv.
    All of my attempts to understand and fix the problem have been futile so far. Could a heavy RMI load between my server and servlet be causing my threads to block? Should I decrease my RMI traffic?

    You have the same problem I had. You need to set the timeout .. so once the timeout is exceeded, an exception is thrown. You need to create a custom RMISocketFactory ... trust me, its easier than it sounds ..check the answers to my post at:
    http://forums.java.sun.com/thread.jsp?forum=58&thread=167287
    hope that helps.

  • Blocked Contacts for iPhone 6 and the call-waiting distinctive ringtone

    Does anyone know if you block a contact on an iPhone 6 and you both have Verizon, will the call waiting distinctive ring still work (The caller hears a ring and beep if you are on the other line)? Or does it only work for non-blocked contacts? Thanks!

        Hi 808iphoneuser,
    Unwanted calls can be annoying! Just to clarify, which block are you using? There is a block that comes on the iPhone 6 that can be placed via the device, or have you placed the VZW Call & Message block  http://vz.to/MqEgqB  on that number?
    Thanks,
    PamelaF_VZW
    Tweet us @vzwsupport

  • TS3406 I am unable to see an incoming call and use call waiting if  I am on a phone call!

    Sprint says its an Apple Problem... Anyone else having this happen?

    Call Waiting is a carrier feature, contact the carrier to troubleshoot.

  • $25 Reward - Calling a CFC via Remote Object or Web Service without making the result public

    I am just getting into Flex 2, so please forgive me for my
    newbe vocab.
    Here is how my applications have worked in the past, i.e.
    ColdFusion:
    <cfscript>
    //Create an instance of component
    order = CreateObject( 'component', 'PEK.Catalog.Order' );
    //Call methd
    theOrder = order.getOrder(1234);
    </cfscript>
    Display the order via HTML and CFML.
    getOrder() returns a query and 1234 is a sample orderID. The
    most important part of the solution I am looking for is that the it
    must not expose my getOrder() as a public web service. I am able to
    run the application with WS by making the mothod URL visible and
    remote, but this is no way near the security I would like to have.
    Here is my folder structure where components folder has been maped
    to CF.
    Application
    |__extentions
    | ... |__components
    | ... ... |__PEK
    |__wwwroot
    I guest there should be a way to call CFC with the thing
    remote object that I have no idea how to set up. So please what
    would be a solution to my security issues.
    Thank you in advance!

    Click
    Here for Link to Article
    I guess this article answers part of the question. It is very
    important to note that if the CFC is sitting on the same server as
    the CFC the component methods could be public and not remote, thus
    making it alot more secure.

  • RMI and Threading: Urgent, pls help!

    Hi everyone,
    I read the previous topics in multithreading but i'm still confused about how RMI works in this case.
    I have a client server application with RMI where client runs some time-consuming executables on the server.
    (i use Process proc = Runtime.getRuntime().exec(cmd...)...)
    Basically I want to make sure that simultaneous requests from different clients execute concurrently, instead of waiting for each other to finish. So my questions are:
    1) When mutiple clients are making remote calls, does RMI map each client request to separate thread and execute them simultaneously (if yes, does it have some limit on number of threads that can be created?);
    Or will I have to take care of creating threads on the server side for each request myself? if the later is the case, how could I go about doing that?
    2) What if all (or some of) the clients are connected from the same VM? How can I ensure that they get executed in different threads, concurrently. Could you pls direct me to ways of implementing it.
    any help is greatly appreciated,
    yulduz

    1) When mutiple clients are making remote calls, does RMI map each client request to separate
    thread and execute them simultaneously (if yes, does it have some limit on number of threads
    that can be created?); Yes, RMI takes care of launching a thread on each remote call. It actually maintains a pool of threads from which, a free thread is assigned a new request. From then on, you have different threads running in server VM (one per each client call).
    Or will I have to take care of creating threads on the server side for each request myself? if the
    later is the case, how could I go about doing that?No, you dont have to create any thread just for the purpose of handling a remote call.
    2) What if all (or some of) the clients are connected from the same VM? How can I ensure that
    they get executed in different threads, concurrently. Could you pls direct me to ways of
    implementing it.You dont have to do anything extra for achieving this. It doesnt matter whether you are running clients in the same VM or different VMs. If you want concurrency on the client side, you have to make remote calls from different threads. The following code outlines the difference between concurrency and non-concurrency in client VM (and NOT server VM).
    class CallerThread extends Thread {
         public void run() {
              remoteRef.callMethod();
    public class Client {
        ... main() {
            // these are not concurrent in client VM bcos the second call happens only after first one       returns
            remoteRef.callMethod1();        
            remoteRef.callMethod2();
            CallerThread t1, t2;
            // these two calls are concurrent on the client side as they're called from two different threads
            t1.start();        
            t2.start();
    }regds,
    CA

  • Have thread in wait, but calling notifyAll() does nothing

    I'm trying to learn how wait() and notify() work with Threads, and I've created the following classes to test them out. However, when I call notifyAll() to restart the other thread, my program just sits there. Doesn't exit or anything. Could someone please help me figure out what is happening?
    Here is my code:
    //my thread class, initializes variables and contains the methods to call wait, notify and run()
    public class MyRunClass extends Thread{
    public boolean A;
    int startNum;
         int endNum;
         public MyRunClass(int y, String name){
              super(name);
              startNum = y;
         public synchronized void passStartNum(){
              endNum = 10;
              if(startNum > 5){
                   startNum = 4;
                   endNum = 10;
                   try{
                        System.out.println(getName() +" going into wait " );
                        wait();
                   }catch(InterruptedException a){
                   System.out.println("falling out of wait");
              }else{
                   endNum = 5;
         public synchronized void myloop(){
              while(startNum < endNum){
                   System.out.println(getName() +" startNum: " + startNum +
    "end Num: " + endNum);
                   try{
                        Thread.sleep(100);
                   }catch(InterruptedException e){}
                   startNum++;
              if(getName().equals("Thread1")){
                   System.out.println("going to do notify");
                   notifyAll();
         public void run(){
              passStartNum();
              myloop();
    //my class with the main() and the creation of my two threads
    public class AThread{
         Thread myt;
         Thread myt2;
         public AThread(){
              myt = new Thread(new MyRunClass(1, "Thread1"));
              myt2 = new Thread(new MyRunClass(6, "Thread6")) ;
         public void startTh(){
              myt2.start();
              myt.start();
         public static void main(String args[]){
              AThread at = new AThread();
              at.startTh();
    //Any help would be really appreciated!! Thanks!

    The other responses are correct, but since this threads are a complicated topic, I'll add another rewording.
    You can only call wait or notify on an object when you have that Object's monitor/lock, that is when you are synchronized on that object. ie...
    Object lock = new Object();
    synchronized (lock) {
        lock.wait();
    }When a thread calls wait, it releases the lock, which enables another thread to grab the lock - possibly to call notify on the object, which would wake up a thread waiting on that object. (notifyAll wakes up every thread that is waiting on that object) Note that the newly-woken thread(s) still won't be able to run until the thread that called notify releases the lock, since they are still in a synchronized block.
    In terms of design, if you want a single thread to wait and be woken it is appropriate to call wait and notify on the thread in question. If you are running multiple threads, and are waiting to synchronize between the threads, it is often more appropriate to call wait and notify on an object shared amongst the threads.
    There are a barrage of articles and lessons on the net... try a search on thread monitors or synchronization.
    -Troy

  • Communication Error with Host and Remote Object

    Hi,
    I was executing my RMI program in a Linux Grid Network environment and the communication was no problem and the code did work.
    However I have switched to the same code to another network with linux machines and when try to execute the code I get the Error:
    java.rmi.ConnectIOException: Exception creating connection to: 136.186.14.96; nested exception is: java.net.NoRouteToHostException: No route to host
    136.186.14.96 is the place where the registry is running and Server Object is bound
    Client Locate the Registry as below
    LocateRegistry.getRegistry("136.186.14.96",1099);
    ACTUAL CODE:
    +//Pass The Remote Reference+
    +try {+
    oClient.registry = LocateRegistry.getRegistry(oClient.o_RegistryReference,oClient.i_Port);
    oClient.server = (ART_Interface) oClient.registry.lookup("Server_Obj");
    oClient.server.clientRegister(oClient.i_ClientID, oClient);
    System.out.println("SEQUENCE <1>  Client [" iID + "] Request to Register");+
    +} catch (Exception e) {+
    System.out.println("Client [" oClient.i_ClientID + "]Registration Error: " + e);+
    +}+
    Client Code Execution....
    +#ART_CLIENT <HOST> <PORT> <Client ID> <slavesPerClient>+
    java -cp /home/research/mbcooray/network/mercury/GRID/ -Djava.rmi.server.codebase=file:/home/research/mbcooray/network/mercury/GRID/ -Djava.security.policy=/home/research/mbcooray/network/mercury/GRID/Policy.txt ART_Client 136.186.14.96 1099 0 1 &

    No for multiple instances of clients communicating (Reporting) to Server, wouldn't server have a dedicated port for them?No. A remote object is exported on port X, the client forms an inbound (from the server's point of view) connection to it, an accepted-socket is created, also on X. netstat -an will show you that: X LISTENING and zero or more X ESTABLISHED. A TCP connection consists of the tuple {TCP, client-address, client-port, server-address, server-port}. Here 'server-port' is X, 'client-port' is allocated by the system. So there can exist multiple inbound connections to X, and the server-port number is always X.
    For Call backs I guess JVM gets hold of a random free portFor all outbound connections, TCP gets hold of a random free port.
    as it is running on a separate thread (I assume)Threads have nothing to do with it.
    Is this done by using socketfactory? Forget it. You don't want to do this, for the reasons I have. You probably don't need to do it, and if you do need to do it you should shoot the netadmin instead.
    Yes, the server exports the object and binds it in the local registryThat's not the same thing as exporting it on port 1099. You can specify a port number when exporting, or when calling super() if your remote objects extend UnicastRemoteObject. If you are using LocateRegistry.createRegistry(), port 1099 will get reused automatically for all subsequently-exported remote objects unless you are using a socket factory, which you aren't. If you are using a separate Registry you should specify the export port number yourself, and you can't re-use 1099.
    The background to this is that firewalls often contain rule configurations about what remote port numbers may be connected to, which corresponds to the reality that Internet services have fixed port numbers, so you can decide e.g. to allow your users to connect to HTTP servers (80,443,8080,8443) and SSH (22) but not for example Telnet (23). However by symmetry they often also allow similar rules for outbound port numbers, which are completely useless as they do not correspond to any reality whatsoever. If you have a netadmin who is enforcing outbound port number rules, just tell him to stop it.

  • What is the difference between RMI and JAX-RPC?

    Dear All
    First of all my understanding of RMI and JAX-RPC:
    RMI is JAVA only version of RPC. It can't talk to any other language.
    JAX-RPC is a part of JWSDP and if you implement your client and server with JAX-RPC, client written in any language can talk with JAX-RPC implementation.
    What else makes them different and am I right with my understanding?
    Finally, I would like to develop clients which will have a java class, say httpserver.java, which will act like a http server, listens to a http port. Now, Two such client will run in two different PC and I want to call a module from one client to another which should be accessible via my httpserver.java. For that which should be my choice RMI or JAX-RPC? Can I achive it with http get-post method, as I am expecting to read some value of variables from one client to the another.
    Say class A has variable a, aa, aaa and clas B has variable b, bb, bbb. Now I want to read the value of b, bb, bbb from class A. How do I do that when class B is listening to a http port with my httpserver.java class.
    Lastly, say B is listening to a http port and I want to send a file to B from A. How can I do that? Remember, B didn�t ask for that. How can A send a file to B when B is listening to a http port with my httpserver.java.
    With regards
    Mohammed Jubaer Arif
    Mobile: +61-0411215302
    Personal Web: http://www.geocities.com/jubairarifctg/
    Org. Web.: http://www.geocities.com/halimschamber/

    simply put, RMI allows you to (semi) transparently treat remote objects as if they were local, and your distributed application can be written (more or less) like a "normal" java app. Sockets just give you a "raw" connection to work with, and you get to build up your application from that.
    I hope that helped
    Lee

  • Thread CPU time: does it include the time while thread is waiting

    Hi,
    My question is regarding the getCurrentThreadCpuTime() supported by the ThreadMXBean.
    I wonder if the returned time includes the time while the thread is waiting, i.e. after the thread calls wait() and before getting a notify() or a notifyAll().
    Thanks,
    Nuha

    CPU time is intended to reflect actual time executing on a CPU. If block for a lock/wait/sleep or other blocking operation like I/O then you don't consume CPU while blocked.
    On Solaris it is implemented using gethrvtime()
    If a VM used a busy-wait for something rather than blocking (not likely with wait()) then that's consuming CPU time.

  • Two remote objects calls on the same php class

    Hi to all,
           I've encountered a strange issue while developing with remote objects.
    I've a mxml component with an init() method inside which is called by a menu.
    When the init() method is called it makes 7 remote object calls which are bound to some components' dataprovider.
    Among this calls I've got 2 remote object which refer to the same remote class. This because I have to call the class twice and the bind the result to two different combobox. Below you find the code:
    <mx:RemoteObject id="myFile" source="myRemoteClass" destination="amfphp"  showBusyCursor="true" makeObjectsBindable="true" fault="traceFault(event)"/>
    <mx:RemoteObject id="myXls"  source="myRemoteClass" destination="amfphp"  showBusyCursor="true" makeObjectsBindable="true" fault="traceFault(event)"/>
    in the init function I make this calls:
    myFile.listDir("dir_1")
    myXls.listDir("dir_2")
    then in the mxml code I bound the result of myFile to combobox1 and the result of myXls on combobox2.
    The problem arise when I call the myXls' listDir method. When I call it I receive the following error:
    code:
    Client.Error.DeliveryInDoubt
    Message:
    Channel disconnected
    Detail:
    Channel disconnected before an acknowledgement was received
    The strange thing is that not only the myXls object returns this error, but also all the other 6 remote object return the same error above.
    I'm not sure, but I guess that the error could be caused by the two remote object which call the same php remote class. If I comment one of the two calls everything works fine.
    Do you have any suggestion about?
    Thanks!!
    Bye
    Luke

    Hi Jan.
    1) We have the 2 VO, each with 3 rows to fill in data. What I mean is that when i just fill in all the fields for the first row of the first VO, and the value of one of these fields is bigger than 50, then after the exception is thrown and the message is displayed, the fields for the first VO are duplicated and shown in the second VO as if the user had inserted them.
    2) We tried yesterday the validateEntity and a Method and Atributte Validator approaches after reading that white paper with the same results.
    The validation is correctly done using any of the those methods.
    I will try to reproduce this issue with the HR schema.
    Thanks in advance once again.

  • Possibility of disabling call waiting prior to receiving an important call?

    I am aware that I can set 'do not disturb', and allow certain numbers to ring. The problem is, I am scheduled for a phone interview -- from a university. This means that a. they will call me (obv.), and b. the actual phone# the call comes from could be a different line from that of the phone being dialled, depending on their phone system's call-routing system.
    In fact, what our phones need as a feature, is the ability to decide on the fly that a call is important, and turn call waiting off at the touch of a button. If I'm writing down directions to the hospital upon receiving news of a family emergency, I don't want to be interrupted, but stuff like this -- or an incoming call from a potential employer to arrange an interview -- can't be planned for ahead of time, and unnecessary increase the user's stresss level.
    Any solid knowledge or creative workarounds welcome. (And yes, a land-line number is better for phone interviews. Problem is, I will be at work and doing the interview on my break.)
    I have iPhone 4S; am running iOS 7.1.1, updated yesterday.

    I've found that simply ignoring call waiting prevents me from being interrupted by other calls. Just because someone calls doesn't mean you have to answer it. However, your carrier may also have a two digit code you can dial to disable call waiting before making a call. For example, with Verizon, it's *70.

  • Call Waiting Question

    Hi,
    I'm using Blackberry 8520 for the frist time after being a loyal consumer of Nokia phones for almost 10 years. I was just wondering on it's call function, howcome I don't get to see that I am "on waiting" when I call someone who is engaged in another call and his Call Waiting function is enabled?
    I would like this feature or function be enabled or present to know if I'm on Waiting rather than wait for them to answer so I can hang-up just in case the aprty I'm calling is on a call...
    Is this something we can enabled or network related or what???
    Hope to find answers here...

    Hi benmarlowe6380,
    This feature is not available in BlackBerry device. I know you're using this feature in other vendors device. In the mean time I can give you a tip to identify whether the person is already in call or not. If you (A) call B and it connects/rings almost instantly then the person in a call. But if the call connects/rings with slight delay then the call is not waiting.
    I know this not a useful use to figure out call waiting but let us hope that some day it might be integrated in BBs as well. 
    tanzim                                                                                  
    If your query is resolved then please click on “Accept as Solution”
    Click on the LIKE on the bottom right if the post deserves credit

Maybe you are looking for