Skip to main content

Socket (TCP & UDP) communication in Java

Socket communication in Java enables communication between two endpoints over a network. There are two main types of sockets: TCP sockets and UDP sockets. Let's explain both types with examples: TCP Socket Communication: 1. **Server Side**:    - The server creates a `ServerSocket` object to listen for incoming connections on a specific port.    - When a client connects, the server accepts the connection and creates a `Socket` object to communicate with the client.    - The server reads from and writes to the socket's input and output streams to communicate with the client. import java.io.*; import java.net.*; public class TCPServer {     public static void main(String[] args) throws IOException {         ServerSocket serverSocket = new ServerSocket(12345);         System.out.println("Server started. Waiting for client...");         Socket clientSocket = serverSocket.accept();         System.out.println("Client connected.");         BufferedReader in = new Bu

Java finalize() Method

Java finalize() Method

Overview:


- Purpose: The `finalize()` method in Java is used for performing cleanup operations or releasing resources before an object is garbage-collected.


- Invocation: The `finalize()` method is automatically invoked by the garbage collector just before an object is reclaimed.


- Class Involvement: The `finalize()` method is defined in the `Object` class, and any class can override it to customize cleanup actions.

Example:

public class ResourceHolder {


    // Some resource or setup in the constructor

    public ResourceHolder() {

        System.out.println("ResourceHolder object created");

    }


    // Cleanup or resource release in the finalize method

    @Override

    protected void finalize() throws Throwable {

        try {

            // Cleanup operations

            System.out.println("ResourceHolder object being finalized");

        } finally {

            // Call the finalize method of the superclass

            super.finalize();

        }

    }


    public static void main(String[] args) {

        // Creating an instance of ResourceHolder

        ResourceHolder resourceObj = new ResourceHolder();


        // Assigning reference to null, making it eligible for garbage collection

        resourceObj = null;


        // Explicitly triggering garbage collection (for demonstration purposes)

        System.gc();

    }

}


Explanation:


1. Object Creation:

   - An instance of the `ResourceHolder` class is created using the constructor.


2. Reference Assignment:

   - The reference `resourceObj` is set to `null`, making the object eligible for garbage collection.


3. Garbage Collection:

   - The `System.gc()` method is called to suggest garbage collection (for demonstration purposes). Note that calling `System.gc()` doesn't guarantee immediate garbage collection; it's a suggestion.


4. Finalization:

   - When the garbage collector determines that there are no more references to the object, it invokes the `finalize()` method.

   - The `finalize()` method contains cleanup operations or resource release logic specific to the `ResourceHolder` class.


Important Notes:

- Explicit Invocation: It's generally not recommended to rely on the explicit invocation of `finalize()` or use it for critical resource management.

  

- Resource Management: For better resource management, consider using other mechanisms such as the `try-with-resources` statement introduced in Java 7.


- Deprecation Warning: The `finalize()` method is not guaranteed to be called promptly or at all. It may be deprecated in future Java versions.


Remember: While understanding `finalize()` can be useful, modern Java applications often use more reliable approaches for resource management and cleanup.



-------------------------------------------------------------


The `finalize()` method in Java is a special method provided by the Java runtime environment for garbage collection. It belongs to the `Object` class and is called by the garbage collector before reclaiming the memory occupied by an object that is no longer reachable or has no more references to it.


Here are some key points about the `finalize()` method:


1. Purpose: The `finalize()` method is used to perform cleanup or resource release operations before an object is garbage collected.


2. Signature: It has the following signature:

 

   protected void finalize() throws Throwable


3. Visibility: The `finalize()` method is `protected`, which means it is accessible only within its own class and subclasses.


4. Invocation: The `finalize()` method is invoked by the garbage collector when it determines that there are no more references to the object. However, it is important to note that there are no guarantees on when or if the `finalize()` method will be called.


5. Usage: While the `finalize()` method can be overridden in a class to provide custom cleanup logic, it is generally not recommended to rely on it for critical cleanup operations. It is better to explicitly release resources using `try-with-resources` blocks or by implementing the `AutoCloseable` interface.


6. Performance: Overriding `finalize()` can have performance implications because the garbage collector has to spend additional time invoking it for each eligible object.


Here's an example illustrating the usage of the `finalize()` method:



public class Resource implements AutoCloseable {

    private String name;


    public Resource(String name) {

        this.name = name;

    }


    @Override

    protected void finalize() throws Throwable {

        try {

            // Cleanup or resource release operations

            System.out.println("Finalizing resource: " + name);

        } finally {

            super.finalize();

        }

    }


    @Override

    public void close() {

        // Explicit resource release method

        System.out.println("Closing resource: " + name);

    }


    public static void main(String[] args) {

        // Creating a resource object

        Resource resource = new Resource("TestResource");


        // Discarding the reference

        resource = null;


        // Triggering garbage collection

        System.gc(); // Note: Requesting garbage collection, but not guaranteed to invoke finalize()

    }

}



In this example, the `finalize()` method is overridden to perform resource cleanup when the object is garbage collected. However, it is also advisable to use the `close()` method for explicit resource release, which can be called directly by the application. Additionally, calling `System.gc()` requests garbage collection but does not guarantee that the `finalize()` method will be invoked.

Comments

Popular posts from this blog

Method Overloading in Java

Method Overloading in Java Method Overloading  is a feature in Java that allows a class to have multiple methods with the same name but different parameter lists. The methods can have a different number or types of parameters. The decision on which method to invoke is made by the compiler based on the arguments provided during the method call.  Example: public class Calculator {     // Method to add two integers     public int add(int a, int b) {         return a + b;     }     // Method to add three integers     public int add(int a, int b, int c) {         return a + b + c;     }     // Method to add two doubles     public double add(double a, double b) {         return a + b;     }     // Method to concatenate two strings     public String concatenate(String str1, String str2) {         return str1 + str2;     } } Method Overloading in Action: public class Main {     public static void main(String[] args) {         Calculator calculator = new Calculator();         // Overloaded meth

Java Runtime Environment (JRE)

Definition : Java Runtime Environment (JRE) is a set of software tools and libraries that enables the execution of Java applications. It provides the necessary runtime support for Java programs to run on various devices and platforms. Components of Java Runtime Environment (JRE): Java Virtual Machine (JVM): Definition: The JVM is a crucial component of the JRE responsible for executing Java bytecode. Functionality: It interprets Java bytecode or, in some cases, uses Just-In-Time (JIT) compilation to translate bytecode into native machine code for improved performance. Importance: JVM abstracts the underlying hardware, allowing Java programs to be platform-independent. Class Libraries: Definition: JRE includes a set of precompiled classes and methods that Java applications can utilize. Functionality: These classes cover a wide range of functionalities, from basic data structures to networking. Importance: Class libraries provide a foundation for developers, offering reusable code