Reputation: 71
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
Upvotes: 2
Views: 1953
Reputation: 5585
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.
datagramSocket
a property of the class.Upvotes: 2
Reputation: 62
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
Upvotes: 0
Reputation: 1086
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.
Upvotes: 0