0

Lets say I have a Jersey-service inside a grizzles server and I like to share data between the server and the service-implementation (e.g. mydata).

public class MyServer 
{  
    String mydata="";

    public static void main (String [] args)
    {
        ResourceConfig rc = new ResourceConfig ().packages (MyServer.class.getPackage ().getName ());
        HttpServer hs = GrizzlyHttpServerFactory.createHttpServer (URI.create ("http://localhost/myserver"), rc);

        for (int i = 0; i < 10; i ++)
        {
             mydata += "bla";
        }

        hs.shutdown ();
    }
}



@Path ("myservice")
public class MyService 
{
        @GET
        public String getIt() 
        {
            // how to access mydata?
        }
}

Whats the best way to share that data? I can think of a singleton or make mydata static. But maybe there is a standard-way I do not see here?

Thanks!

chris01
  • 10,921
  • 9
  • 54
  • 93

1 Answers1

1

You can make mydata static or instance variable of singleton if and only if mydata is really static and cannot be changed by multiple threads (e.g. inside your getIt() method of the service).

Such technique applies and uses usually for common configuration properties.

In general it is a standard way for such situation. BTW you can keep your mydata not necessary in the Server class, but make another class to keep such common data there (if there are bunch of them) , but it is a matter of choice.

Also it is more standard to do not make actual mydata field public , but provide getter/setter pair for it.

Finally, if such common/static value can be changed by multiple threads you need to make it synchronized to avoid concurrent modifications.

There are much more different approaches to handle concurrency and make code thread-safe, but it belongs to your actual needs. Anyway all of them end up to static/singleton synchronized implementation.

PS. Be careful, if it is a common static data you have to populate it before start the server not after (as in your example) - otherwise there is a possibility that request may come before data ready to use by service thread.

Vadim
  • 4,027
  • 2
  • 10
  • 26
  • I already figured out it is also about threads/concurrency. But I was looking for a way to provide a reference to the data inside the server. As I can give a reference to objects into the Thread-constructor. But if that is not possible I need to use statics. – chris01 Jul 13 '18 at 13:19
  • I did not get what you are looking for. In Java everything is a reference to an object even Class and its static members. (Only primitives pass by value in method calls). Main question is only about where that object actually lives to be referenced when needed. – Vadim Jul 13 '18 at 20:46