2

Can anyone explain to me the scope of creating an object from a class inside a method in java, is it a bad way and wasting the resources or it's normal? The program is running but I am not sure about this step:

/**
 * Sending Packets Method
 * @param message-the message we want to send to the client side
 * @param IP-in InetAddress format
 * @param Port-in integer format
 * @return Null
 */
public static void send(String message,InetAddress IP,int Port){
    byte [] buffer=message.getBytes();
    DatagramPacket datagrampacket=new DatagramPacket(buffer,buffer.length,IP,Port); 
    datagrampacket.setPort(20002);
    try {
        DatagramSocket datagramSocket=new DatagramSocket();
        datagramSocket.send(datagrampacket);
        datagramSocket.setReuseAddress(true);
        datagramSocket.close();
    } catch (SocketException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
}

In this case, I create a new object of DatagramSocket every single time I call the function and wasting the resources or the object disappear when the function finishes?

Thanks

Martin Spamer
  • 5,437
  • 28
  • 44
KamelK
  • 71
  • 9
  • the scope of "creating an object from a class" ? do you mean the scope of where a variable can be used? that depends on where it was declared. – Stultuske Jul 18 '18 at 10:29
  • 1
    But, yes, in this code, you'll create a new instance of DatagramSocket each time you call this method (java doesn't have functions), and it will indeed be ready for GC on termination of the method. – Stultuske Jul 18 '18 at 10:30
  • 2
    This is not ideal, no. You would want to open the socket and keep it open. Opening IO sockets is really rather expensive... – Boris the Spider Jul 18 '18 at 10:33
  • thanks... I am calling the sending function from the main class every a few minutes and that function creates the object of the "DatagramSocket"....so thats ok? – KamelK Jul 18 '18 at 10:34
  • @KamelK it 'll work, but whether it's "OK" is a different matter. It might be (a lot) better if you created an instance on startup of your application and kept re-using that instance, instead of constantly creating new ones. Basically, you are throwing away your systems resources – Stultuske Jul 18 '18 at 10:35
  • Depends, do you need your code to be performant or Just Work TM? Do you care about performance? If this is a toy project, it's probably fine. If this is production code, then I would aim to change the code to keep the socket open. – Boris the Spider Jul 18 '18 at 10:35
  • so I have to create the object of the datagram socket inside the main class and pass it to the method every time I have to use it...right? – KamelK Jul 18 '18 at 10:36
  • Or you could write OO code. Remove every `static` you see. Keep resources as instance variables inside the lifecycle of the objects that use them. Use IoC to inject those resources in those classes. Then add a DI container to wire everything together. In other words, you _could_ write actual Java. – Boris the Spider Jul 18 '18 at 10:37
  • ok thanks everyone for offering knowledge ...i will try to change it by creating the datagramsocket object inside the main class..thanks – KamelK Jul 18 '18 at 10:39
  • @KamelK if you declare it as a class or instance member, you won't need to pass it as a parameter each time you call the method – Stultuske Jul 18 '18 at 10:40
  • @Stultuske i am using the send method many times in the main class so that's why i have to pass the object of the datagramsocket after creating it from the main class to the send method to send the packet – KamelK Jul 18 '18 at 10:51
  • @KamelK no, you don't. if it's declared as a class or instance variable, depending on whether your method is static or not, the method will have access to it, since it's in the scope of the class/instance – Stultuske Jul 18 '18 at 11:01

3 Answers3

2

It is not wrong but it is sub-optimal, a DatagramSocket doesn't qualify as a lightweight class for the purposes of construction on demand. This question would probably receive better answers on SE Code Review.

  • Make the datagramSocket a property of the class.
  • Remove the static from the method.
  • Instantiate the socket in either constructor of this class, or the calling class and pass to the constructor.
  • Your parameter variable 'Port' should be 'port'.
  • Your code ignores the Port parameter and hard codes a socket to 20002.
  • Learn the distinction between variable lifetime and scope.
Martin Spamer
  • 5,437
  • 28
  • 44
0

The scope will be the declaration of the object. To create a object in a function, it depends upon yourrequirement, if you want to reuse the object, then you can declare the object at the class level and make the class as singleton (like using the Database repository) and initilize it in the constructor or some init method. And if you require every method call should have new object, then you should create in method level.

Dinesh
  • 1,046
  • 1
  • 8
  • 17
0

since you are not returning the object to any instance variable, when the methd ends there are no variable pointing to the object so it can be garbage collected. you can not know when the gb will run or if it will. this is just to say you can not assume the object will disappear as soon as the method ends

hipposay
  • 62
  • 2
  • Sorry, this is not an answer. An answer requires evidence, backing, something other than a stream of conciousness. Furthermore, this isn't accruate enough to be answer about programming - what does "dissapear" mean? – Boris the Spider Jul 18 '18 at 10:38
  • the author of the quastion asked if "the object disappear when the function finishes?" – hipposay Jul 18 '18 at 10:42
  • Yes, the author is a student, you are a teacher. Step 1 would be to explain what scoping is, step 2 what eligible for GC is, step 3 explain that this means that "visibility" is different to "deletion" - gc. Step 4, tie it all together with a nice example. A bad question is **not ever** an excuse to write a bad answer. – Boris the Spider Jul 18 '18 at 10:43