There is a class in the constructor of which an asynchronous listening socket is created. All work with the socket is implemented in this class and an external link to this class is not needed.

The question is how correct this method of creating a class object is.

new Server(); 

those. without assigning the created instance to a variable. Will such a garbage collector object?

  • one
    Where is new Server() called? In main() ? - Sergey Gornostaev
  • one
    Is it generally good / beautiful to execute / run a bunch of business logic in the constructor when creating an instance instance? Wouldn't it be better to spend on a minimum initialization through the constructor, and manually run all the logic through a separate method, placing the object instance in the field / variable? - Peter Samokhin
  • Probably "will not beat", but you can probably say only by looking at the code - Ramiz
  • @PeterSamokhin to put the logic in a separate method - yes, but why in this case is the field / variable? new Server().start(); and that's all. - Regent
  • @Ramiz and look at what code you want to say for sure? - Regent

1 answer 1

When each method is called, a stack frame is created. The new operation will place a reference to the object in the stack frame of the method that called it. Even without assigning this reference to a variable, it will be stored on the stack until the method ends and the stack frame is destroyed. And the garbage collector does not touch those objects that are referenced in the stack.

  • Method? Or the current block {...} ? - Anton Shchyrov
  • Method. Blocks can affect the visibility limits of variables, but this language construct also exists only until the time of compilation. There will be no information about the blocks in the bytecode and the virtual machine will not know anything about them. - Sergey Gornostaev