DronaBlog

Showing posts with label Java. Show all posts
Showing posts with label Java. Show all posts

Wednesday, July 24, 2024

What is Thread Contention?

 

Understanding Thread Contention

Thread contention occurs when multiple threads compete for the same resources, leading to conflicts and delays in execution. In a multi-threaded environment, threads often need to access shared resources such as memory, data structures, or I/O devices. When two or more threads try to access these resources simultaneously, contention arises, causing one or more threads to wait until the resource becomes available. This can lead to performance bottlenecks and decreased efficiency of the application.

How Thread Contention Works

To manage access to shared resources, mechanisms like locks, semaphores, and monitors are used. These synchronization mechanisms ensure that only one thread can access the resource at a time. However, excessive use of these mechanisms can lead to contention, where threads spend more time waiting for locks to be released than performing useful work.






Example of Thread Contention

Consider a scenario where multiple threads are updating a shared counter:


public class Counter {

    private int count = 0;


    public synchronized void increment() {

        count++;

    }


    public synchronized int getCount() {

        return count;

    }


    public static void main(String[] args) {

        Counter counter = new Counter();

        Runnable task = () -> {

            for (int i = 0; i < 1000; i++) {

                counter.increment();

            }

        };


        Thread thread1 = new Thread(task);

        Thread thread2 = new Thread(task);


        thread1.start();

        thread2.start();


        try {

            thread1.join();

            thread2.join();

        } catch (InterruptedException e) {

            e.printStackTrace();

        }


        System.out.println("Final count: " + counter.getCount());

    }

}

In this example, the increment method is synchronized, meaning only one thread can execute it at a time. While this ensures correct updates to the shared counter, it also introduces contention when multiple threads try to access the increment method simultaneously.





Real-Time Example of Thread Contention

One notable example of thread contention causing major issues is the early days of Twitter. As the platform rapidly gained popularity, the infrastructure struggled to handle the increasing load. One specific issue was the handling of user timeline updates.

The Twitter Fail Whale Incident

In the early days, Twitter used a single-threaded system to update user timelines. When a user posted a tweet, the system updated the timelines of all followers. As the user base grew, this process became extremely slow, leading to significant delays and failures in updating timelines.

The problem was exacerbated by thread contention. Multiple threads were trying to update the same data structures (user timelines) simultaneously, causing severe contention and bottlenecks. The system couldn't handle the load, leading to frequent downtime and the infamous "Fail Whale" error page.

Resolution

Twitter resolved this issue by moving to a more scalable, distributed architecture. They introduced a queuing system where tweets were processed asynchronously, reducing contention and allowing for parallel processing of timeline updates. Additionally, they optimized their data structures and algorithms to minimize lock contention.


Thread contention is a critical issue in multi-threaded applications, leading to performance bottlenecks and inefficiencies. Proper synchronization mechanisms and architectural changes can help mitigate contention and improve the performance and scalability of applications. The example of Twitter's early infrastructure challenges highlights the importance of addressing thread contention in high-traffic systems.

Thursday, July 11, 2024

What are differences between Daemon thread and Orphan thread in java?

 In Java, the concepts of daemon threads and orphan threads refer to different aspects of thread management and behavior. Here's a detailed comparison:





Daemon Thread

  • Purpose: Daemon threads are designed to provide background services while other non-daemon threads run. They are often used for tasks like garbage collection, background I/O, or other housekeeping activities.
  • Lifecycle: Daemon threads do not prevent the JVM from exiting. If all user (non-daemon) threads finish execution, the JVM will exit, and all daemon threads will be terminated, regardless of whether they have completed their tasks.
  • Creation: You can create a daemon thread by calling setDaemon(true) on a Thread object before starting it. Example:
    Example:
    Thread daemonThread = new Thread(new RunnableTask()); daemonThread.setDaemon(true); daemonThread.start();
  • Usage Consideration: Daemon threads should not be used for tasks that perform critical operations or that must be completed before the application exits.




Orphan Thread

  • Definition: The term "orphan thread" is not a standard term in Java threading terminology. However, it generally refers to a thread that continues to run even though its parent thread (the thread that created it) has finished execution.
  • Lifecycle: Orphan threads are still considered user threads unless explicitly set as daemon threads. Therefore, they can prevent the JVM from shutting down if they are still running.
  • Creation: An orphan thread can be any thread that is created by a parent thread. If the parent thread completes its execution, but the child thread continues to run, the child thread becomes an orphan thread. Example:
    Example:
    Thread parentThread = new Thread(new Runnable() { @Override public void run() { Thread childThread = new Thread(new RunnableTask()); childThread.start(); // Parent thread finishes, but child thread continues } }); parentThread.start();
  • Usage Consideration: Orphan threads are normal user threads, so they need to be managed properly to ensure that they don't cause the application to hang by keeping the JVM alive indefinitely.

Key Differences

  1. JVM Exit:
    • Daemon Thread: Does not prevent the JVM from exiting.
    • Orphan Thread: Can prevent the JVM from exiting if it is a user thread.
  2. Creation:
    • Daemon Thread: Explicitly created by setting setDaemon(true).
    • Orphan Thread: Any child thread that outlives its parent thread.
  3. Use Case:
    • Daemon Thread: Used for background tasks.
    • Orphan Thread: Can be any thread continuing to run independently of its parent thread.

Understanding these concepts helps in designing multi-threaded applications where thread lifecycle management is crucial.

Wednesday, January 3, 2024

Configuring Java Version with the -vm Argument: A Comprehensive Guide

 Introduction:

Java applications are widely used across various industries and platforms, and ensuring the correct Java version is crucial for optimal performance and compatibility. One way to specify the Java version for your application is by using the -vm (Virtual Machine) argument. This article will guide you through the process of adding the -vm argument to ensure your Java application runs on the desired Java version.





Understanding the -vm Argument:

The -vm argument allows you to specify the Java Virtual Machine (JVM) executable that your application should use. This is particularly useful when you have multiple Java installations on your system, and you want to ensure that your application runs on a specific version.

Step-by-Step Guide:

  1. Identify the Java Version:

    • Before adding the -vm argument, you need to identify the path to the Java executable of the desired version on your system. You can do this by running the following command in the terminal or command prompt:

    • java -version

    • Note the installation path of the desired Java version.


  2. Locate Eclipse.ini or STS.ini (for Eclipse-based IDEs):

    • If you are using an Eclipse-based IDE like Eclipse or Spring Tool Suite (STS), locate the configuration file named eclipse.ini or STS.ini. This file is usually found in the root directory of your IDE installation.
  3. Edit the Configuration File:

    • Open the eclipse.ini or STS.ini file in a text editor of your choice.

  4. Add the -vm Argument:

    • Add the following lines to the configuration file, replacing the path with the actual path to the Java executable of the desired version:

    • -vm /path/to/java/executable

    • Make sure to add these lines before any other -vmargs or -XX options in the file.


  5. Save and Restart:

    • Save the changes to the configuration file and restart your IDE.





  6. Verify the Configuration:

    • After restarting the IDE, verify that it is using the correct Java version by checking the version information in the IDE or running the following command:

    • java -version

    • Ensure that the displayed version matches the desired Java version.


Configuring the Java version for your application using the -vm argument is a straightforward process that ensures your code runs on the intended Java Virtual Machine. Whether you are working on an Eclipse-based IDE or another Java development environment, following these steps will help you set up the correct Java version for your projects, avoiding compatibility issues and ensuring optimal performance.





Thursday, November 9, 2023

What is JMS (Java Message Service) ?

JMS, or Java Message Service, is a Java-based API that allows applications to create, send, receive, and read messages in a loosely coupled, reliable, and asynchronous manner. It's commonly used for communication between distributed systems or components.



Here's a brief overview of how JMS works: Messaging Models:

  • JMS supports two messaging models: Point-to-Point (P2P) and Publish/Subscribe (Pub/Sub).
  • P2P involves sending messages to a specific destination where only one consumer can receive the message.
  • Pub/Sub involves sending messages to a topic, and multiple subscribers can receive the message.

Components:

  • JMS involves two main components: Message Producers and Message Consumers.
  • Message Producers create and send messages to a destination.
  • Message Consumers receive and process messages from a destination.

Connections and Sessions:

  • JMS uses ConnectionFactory to establish a connection to a JMS provider (like a message broker).
  • Sessions are created within a connection to manage the flow of messages. They provide a transactional boundary for message processing.

Destinations:

  • Destinations represent the place where messages are sent or received. In P2P, it's a queue, and in Pub/Sub, it's a topic.

Messages:

  • JMS messages are used to encapsulate data being sent between applications. There are different types of messages, such as TextMessage, ObjectMessage, etc.

Message Listeners:

  • Message Consumers can register as message listeners to asynchronously receive messages. When a message arrives, the listener's onMessage method is invoked.

Acknowledgment:



  • Acknowledgment is the mechanism by which the receiver informs the JMS provider that the message has been successfully received and processed.

Transactions:

  • JMS supports transactions, allowing multiple messaging operations to be grouped together. Either all operations succeed, or they all fail.

JMS provides a flexible and robust way for Java applications to communicate through messaging, facilitating reliable and asynchronous communication between different components in a distributed system.

Learn more about Java here




Wednesday, April 5, 2023

What is Bug, Error and Issue?

In the world of software development, terms like "bug," "error," and "issue" are often used interchangeably. However, there are subtle differences between these terms that can be important to understand, especially when communicating with other developers or stakeholders. In this article, we'll explore the differences between these three terms and how they relate to software development.






A. Bug:

A bug is a defect or flaw in the software that causes it to behave in an unintended way. This can result from a coding mistake or a problem with the software's design. Bugs can range in severity from minor glitches to major issues that prevent the software from working at all. They are typically discovered during testing or after the software has been released and are often fixed by the development team through a software update or patch.


B. Error:

An error is a mistake made by a programmer during the coding process. Errors can be syntax errors, where the code does not conform to the language's rules, or logic errors, where the code does not perform the intended function. Errors can occur during development or after the software has been released and can lead to bugs or other issues. Programmers can use debugging tools to identify and fix errors in their code.


C. Issue:

An issue is a problem or challenge that arises during the software development process. Issues can include bugs, errors, or other obstacles that affect the software's functionality, performance, or usability. Issues can also arise from external factors, such as hardware or network problems. Tracking issues is an important part of software development, as it allows developers to identify areas for improvement and ensure that the software meets the needs of its users.






In summary, bugs, errors, and issues are all related to software development, but they represent different aspects of the process. Bugs are defects in the software that cause unintended behavior, errors are mistakes made during the coding process, and issues are problems or challenges that arise during development. Understanding these differences can help developers communicate more effectively and improve the quality of their software. 


Learn more



Tuesday, January 24, 2023

What is Null Pointer Error in Java and How to fix it?

Are you looking for what is best way to fix Null Pointer error in your Java code? Are also would like to know what causes Null Pointer error. If so, then you reached at right place. In this article, we will understand what is root cause of Null Pointer error and how to fix it. Let's start.


 A null pointer error, also known as a "null reference exception," occurs when a program attempts to access an object or variable that has a null value. In other words, the program is trying to access an object that doesn't exist. This can happen when a variable is not initialized or is set to null, but the program tries to access it as if it has a value.






The error message will typically indicate the specific location in the code where the error occurred, and it will look something like this: "java.lang.NullPointerException at [classname].[methodname]([filename]:[line number])".


There are several ways to fix a null pointer error, but the most common solution is to check for null values before trying to access an object. This can be done by using an if statement to check if the variable is null, and if so, assign a value to it or handle the error in a specific way.


Another way is to use the "Optional" class introduced in Java 8, it allows to avoid null pointer exceptions. It can be used with any type of variable and it wraps the variable and it can check if it's present or not.


For example, if the error occurs when trying to access an object called "objectName," the following code can be used to fix it:


if (objectName != null) {

    // code to access objectName

} else {

    // handle the error or assign a value to objectName

}






Additionally, you should check that the objects that you're using are not null, it's also important to check that the objects that the object you're using is not null. To avoid this error, it's important to initialize variables and objects properly and to be aware of the scope of the variables and objects that you're using in your code.

In summary, a null pointer error occurs when a program tries to access an object or variable that has a null value. The error can be fixed by checking for null values before trying to access an object and handling the error properly. It is important to initialize the variables and objects properly, check for the scope of the variables and objects, and to be aware of the potential of null values.

Learn more about Java usage here-




Wednesday, January 4, 2023

How to connect to Database in Java?

 To connect to a database using Java, you will need to use the JDBC (Java Database Connectivity) API. This API provides a standard set of interfaces for connecting to a database, executing queries, and processing the results.





 

Here is an example of Java code that demonstrates how to connect to a database using JDBC:

 

import java.sql.Connection;

import java.sql.DriverManager;

import java.sql.SQLException;

 

public class DatabaseConnection {

 

    public static void main(String[] args) {

 

        // Load the JDBC driver

        try {

            Class.forName("com.mysql.jdbc.Driver");

        } catch (ClassNotFoundException e) {

            e.printStackTrace();

            return;

        }

 

        // Establish a connection to the database

        Connection connection = null;

        try {

            connection = DriverManager.getConnection(

                "jdbc:mysql://localhost:3306/mydatabase", "username", "password");

        } catch (SQLException e) {

            e.printStackTrace();

            return;

        }

 

        // Do something with the connection, such as executing a query

        // (omitted for brevity)

 

        // Close the connection

        try {

            connection.close();

        } catch (SQLException e) {

            e.printStackTrace();

        }

    }

}

 

 





In this example, we first load the JDBC driver for MySQL using the Class.forName() method. Then, we use the DriverManager.getConnection() method to establish a connection to the database. Finally, we close the connection using the Connection.close() method.

 

Note that this example uses MySQL as the database, but you can use a different database by simply changing the JDBC driver class and the connection URL. You will also need to provide the appropriate username and password for the database.

Saturday, November 6, 2021

What is difference between HTTPS , SSL and TLS ?

                  Are you looking for details about HTTPS protocol? Are you also interested in knowing the differences between HTTPS, SSL, and TLS? If so, then you reached the right place. In this article, we will learn more about HTTPS, SSL, and TLS. Let's start.


A) Understand the speed of the data 

               The data sent over the internet is very fast. It is faster than traditional channels such as wires, optic fiber, air. It will not be an exaggeration if we say data send over the internet with speed of light. Even speed of data sent over the internet is fast, but it still has to go through multiple devices during its journey over the network and that is where criminals target data.






B) What is HTTPS?

                The internet consists of distributed client and server information systems. When we access any application using a computer or mobile or any other type of device, ( these devices act as the client ) we send the request to the server. The server can accept or reject the request. If the request is accepted then a connection is created over a specific protocol. In order to establish a communication set of rules which are implemented with the protocol.

                 HTTP stands for Hypertext Transfer Protocol used on the worldwide web(www). This commonly used protocol defines 

                                   1. How data is formatted

                                   2. What type of data is to be transmitted 

                                   3. How the server should respond to the specific command 

                  However, HTTP is not secure as it does not have data encryption and authentication functionalities. In order to achieve security especially transmitting data over the network, Hypertext Transfer protocol secure (HTTPS) protocol can be used.

                                  Though HTTPS is a safer solution for the client and server models, this added security isn't automatic. In order to maintain security standards, we need to purchase SSL/TLS certificates from a trusted certificate authority.


C) What is SSL? 

                The SSL stands for Secure Socket Layer. The internet connections are maintained safely by SSL encryption and decryption method. These connections can be between client to client or client to server or server to server. As SSL is an older protocol, the updated TLS was released in 1999 and it is being commonly used nowadays.






D) What is TLS?

                 TLS stands for Transport Layer Security. TLS is a cryptographic protocol used for achieving better privacy, data integrity, and authentication compared to SSL. It supports stronger, secure cipher suites and algorithms.

                TLS is more commonly used in computer networks, web browsing, instant messaging, email etc. 


                     Learn more about Java here 




Saturday, October 30, 2021

How does TLS or SSL Decryption work ?

              Would you like to know how does TLS or SSL decryption work? Would you be also interested in knowing Symmetric and Asymmetric cryptography? If so, then you reached the right place. In this article, we will explore decryption with TLS or SSL. Let's start.

A) What TLS or SSL? 

               As discussed in what is the difference between HTTPS, SSL, and TLS  ? article, TLS or SSL is a cryptographic protocol for achieving privacy, data integrity over the network.






B) How does TLS/SSL decryption work? 

               The TLS and SSL both use asymmetric cryptography. TLS /SSL provides reliable security with high performance.

                a) Symmetric Cryptography :

                     Symmetric cryptography uses a secret key to encrypt data. The generated secret key is shared with the sender and receiver. The secret key should be 128 bits in length in order to achieve security.

                 b) Asymmetric Cryptography :

                      Asymmetric cryptography uses private and public keys. The public and private keys are mathematically designed. It requires higher bandwidth. The key length should be a minimum of 1024 bits.

                c) Secure session key : 

                     The secure session key is generated by SSL /TLS by using asymmetric cryptography. The secure session key is used to decrypt and encrypt the data transmitted over the network. secure session the TLS handshake is achieved with the secure session key.






C) What TLS handshake? 

               The TLS handshake is a process to achieve communication between server and client to achieve the below Functionalities -

               1. Acknowledge one another 

               2. Verify each other's authenticity 

               3. Designate encryption algorithms 

               4. Agree on session keys. 




                

Tuesday, October 12, 2021

What are new feature in Java -17 part 2

                Are you interested in knowing what are the new featured introduced in Java 17? Are you also interested in knowing what are the deprecated features in Java 17? If so, then reached the right place. This is the second part of the feature in java 17. You can access the first part of the features of Java 17 here.

A) Introduction 

              In the previous article, we explored the Java 17 features such as JEP 412: Memory API and Foreign Function, JEP 411: Deprecate the Security  Manager, JEP 414: Vector API, JEP 415: Deserialization Filters.

             In this article, we will focus on the features below in Java 17 

           1. JEP 409: Sealed classes 

           2. JEP 406: Pattern Matching for switch 

           3. JEP 403: Strongly Encapsulate JDK internals 

           4. JEP 398: Deprecate Applet API for removal 





B ) JEP 409: Sealed classes 

            A sealed class that restricts other classes may extend it. This also applies to interface as well i.e a sealed class can be an interface that restricts another interface may extend it. 

           With Java 17, new sealed, non-sealed character sequences are introduced and it allows them as contextual keywords.






C ) JEP 406: Pattern Matching for switch 

             With this change, all existing expressions and statements compile with identical semantics. It performs then without any modification.

              There are two new patterns are introduced 

          1. Guarded Pattern: It is used to refine the pattern matching logic using a boolean expression 

          2. Parenthesized Pattern: It is used to get rid of parsing ambiguities 


D ) JEP 403: Strongly Encapsulate JDK internals 

             All the internal elements of JPK are strongly encapsulated. Here only exception is sun.misc.unsafe.


E ) JEP 398: Deprecate Applet API for Removal 

              As we know Applet APIs were deprecated since Java 9 but these were never removed. With Java 17, these will be removed there not be much impact because these Applet APIs are no longer in use as we use more advanced web technologies for it.


                    Learn more about Java here -

            


Sunday, October 10, 2021

What are new Features in Java 17 - Part 1

               Are you looking for detailed information about all the interesting features introduced in JDK 17? Are you also would like various terminologies such as LTS or JEP? If so, then you reached the right place. In this article, we will explore new features in JDK 17 release.

A) What is LTS in Java?

               LTS is an abbreviation for Long-term Support. It is a product life cycle management policy. With this policy, the software edition is supported longer than the software standard edition.






B) What is JEP in Java? 

               JEP is an abbreviation for JDK Enhancement Proposal. Oracle Corporation has drafted this process to collect proposals for enhancements to the Java Development kit i.e. JDK. 


C)  What are the new features in Java 17? 

                Java 17 is one of the major releases and comes with various interesting features. In this article we will explore the features below :

          1. JEP 411: Deprecate the security manager 

         2. JEP 412: Memory API and Foreign Function 

         3. JEP 414: Vector API

        4. JEP 415: Deserialization Filters


1 . JEP 411: Deprecate the security manager 

                  The security manager API which was used to define security policy for an Application is deprecated with JDK 17  release. The security manager is deprecated as this API is not commonly used. one of the basic features of a security manager is a blocking system:: exit. If applications continue to use the security manager then an alert message will be issued.





2. JEP 412: Memory API and Foreign function

                   With JEP 412 the new API is introduced and these are Foreign Memory Access API and the foreign linker API with these API'S we can invoke code outside of the JVM and also security access foreign memory Here, foreign memory means the memory which is not handled by JVM. 

3. JEP 414: Vector API 

                    These Vector APIs are part of JDK 16 are also enhanced in JDK 17 to express vector computations on supported CPU architecture at runtime. These are reliable for compilation and performance on AArch 64 and x64 architectures.

4. JEP 415: Deserialization Filters 

                    With a JVM-wide filter factory, we can allow applications to configure context-specific and dynamically selected deserialization filters. This will be helpful to prevent serialization attacks.


                      Learn more about Java here -



Understanding Survivorship in Informatica IDMC - Customer 360 SaaS

  In Informatica IDMC - Customer 360 SaaS, survivorship is a critical concept that determines which data from multiple sources should be ret...