0

I'm making changes to some java applications and i'm noticing they instantiate the service client in every iteration of the loops, like this:

for(String name : names) {
HelloService helloWS = new HelloService();
HellowServicePort helloPort = helloWS.getHelloServicePort();
helloPort.sayHello(name);
}

Instead of getting the port once, like this:

HelloService helloWS = new HelloService();
HellowServicePort helloPort = helloWS.getHelloServicePort();
for(String name : names) {
helloPort.sayHello(name);
}

Does using the second approach make any difference?

GabrielBB
  • 2,479
  • 1
  • 35
  • 49
  • @11thdimension why would you say " it needs different objects for each call"? – João Rebelo Apr 20 '16 at 16:36
  • @GabrielBB, have you tried the second approach and got some SOAPHandlers to see if you notice any difference? Are you using any JavaEE container? – João Rebelo Apr 20 '16 at 16:38
  • @JoãoRebelo I assume that it would open a socket to send the message. Please correct me if I'm wrong. – 11thdimension Apr 20 '16 at 16:46
  • @11thdimension, The reason that I asked is that I have no idea. But I don't think it directly means opening a new TCP socket. Refer to https://docs.oracle.com/javase/7/docs/api/javax/xml/ws/spi/ServiceDelegate.html#getPort(java.lang.Class). I don't know the specifics of each implementation. But I am assuming that unless he is concurrently using that object he will benefit from not instanciating it multiple times. – João Rebelo Apr 20 '16 at 16:51
  • @JoãoRebelo You're right, there's no need for a new port object, one instance can be reused. I just verified it. – 11thdimension Apr 20 '16 at 18:29

1 Answers1

1

Yes you can reuse the port object multiple times without needing to create a new one.

My previous comment was incorrect as pointed out by JoãoRebelo.

I have verified it with this calculator service

http://www.webservicex.com/globalweather.asmx?WSDL

After exporting the artifacts with the wsdl2java http://www.webservicex.com/globalweather.asmx?WSDL

Following code works perfectly fine.

Calculator calculatorClient = new Calculator();
ICalculator port = calculatorClient.getICalculator();
for(int i = 0; i < 10; i++) {
    float x = (float)Math.random() * 100;
    float y = (float)Math.random() * 100;
    System.out.printf("%f + %f = %f%n", x, y, port.add(x, y));
}
11thdimension
  • 10,333
  • 4
  • 33
  • 71
  • You can link to this to complete your answer with [thread-safety information](http://stackoverflow.com/questions/10599959/is-this-jax-ws-client-call-thread-safe) – João Rebelo Apr 20 '16 at 20:29