Can registry and interface objects for java RMI be declared static globally?

384 Views Asked by At

I seem to have a dilemma. Sparing the complicated details of my project, i'm attempting to do the following. (excluding and replacing some code like imports and try-catch for simplicity)

1  public class Client
2  {
3     private Registry reg1; 
4     private GameSessionInterface sesh1;
5  
6     public static void main(String[] args)
7     {
8        reg1 = LocateRegistry.getRegistry(serverIP, 4200);
9        sesh1 = (GameSessionInterface)reg1.lookup("Session1");
10    }
11 }

On lines 8 and 9 i get the errors "Cannot make a static reference to the non-static field reg1" and "Cannot make a static reference to the non-static field sesh1" respectively.

if i declare reg1 and sesh1 inside of main, i don't get this issue. But i need at the very minimum sesh1 to be global so i can make methods accessing it outside of main.

I'm not 100% sure how RMI variables work in the JVM so I'm unsure whether it's safe to declare these as static. Logic would follow that since i'm not going to be making more than one instance of Client in the same JVM, it shouldn't matter, but considering this is a reference to a remote object, I didn't know if this would have some unseen side effects. I've searched for a while and no one seems to address this. But at the same time I can't seem to find examples of code with these declared statically, which also begs the question why can't I compile it as is when similar code exists elsewhere with non-static declarations made globally.

I'm REALLY new to RMI in java so if any of you with more RMI experience could shed some light on how all this interacts and why I might be getting this error, I would greatly appreciate it.

Thanks in advance!

1

There are 1 best solutions below

0
On

RMI variables are no different from any other variables. You could for example have declared both variables as local within main().

However if you're creating a Registry with LocateRegistry.createRegistry(), it is essential to store it into a static variable. Otherwise it can be garbage-collected and disappear.

the question why can't I compile it as is when similar code exists elsewhere with non-static declarations made globally

No it doesn't. Look again. The rules for static and instance variables are the same throughout Java. RMI does not and cannot change that.