Professional Documents
Culture Documents
Concurrent Programming:
Java Concurrency is the capability of the Java platform to run multiple operations
simultaneously. The operations could be multiple Java programs or parts of a
single Java program. Java Concurrency relies on two essential components such
as threads and processes. Of the two components, threads play a significant role.
With Java Concurrency or using multiple threads, you can enhance the
performance of processors. You don’t need multiple processors for running
concurrent programs in Java; instead, you can use a single multi-core processor.
Know that a multi-core processor will have many cores in a single CPU. All these
multiple cores can run many programs or parts of a program simultaneously.
You are probably familiar with multitasking, which is when someone tries to
perform two or more tasks simultaneously. While people are not very good at
multitasking, it turns out that computers are! It has become increasingly
commonplace for computer systems to have multiple processors, or processors
with multiple execution cores, which greatly enhances a system’s capacity for
concurrent execution of processes and threads.
This process is possible even on simple systems, with only one processor or
execution core. In software terms, performing multiple tasks at the same time is
called concurrency. Concurrency may also be defined as the ability to run several
programs or several parts of a program in parallel.
Why Concurrent Programming?
Concurrent programming is essential in modern computing for several reasons:
i. Performance Improvement: Concurrent programs can utilize multiple CPU
cores efficiently, which can lead to significant performance improvements
for CPU-bound tasks.
ii. Responsiveness: For applications with user interfaces, concurrency
ensures that the application remains responsive even when performing
time-consuming operations in the background.
iii. Resource Utilization: Concurrent programs can make better use of system
resources, such as CPU time, memory, and I/O devices.
iv. Parallelism: Some tasks naturally lend themselves to parallel execution,
like rendering graphics, processing data, or handling multiple client
requests in a server application.
Key Concepts in Concurrent Programming:
➢ Thread: A thread is the smallest unit of execution within a program. It
represents an independent flow of control that can run concurrently with
other threads. Most programming languages, including Java, C++, and
Python, provide thread support.
➢ Process: A process is a self-contained program that runs independently and
has its own memory space. Processes can have multiple threads, and inter-
process communication (IPC) is required for them to communicate.
➢ Concurrency vs. Parallelism: These terms are often used interchangeably,
but they have distinct meanings. Concurrency is about managing multiple
tasks in overlapping time periods, while parallelism is about executing
multiple tasks simultaneously.
➢ Synchronization: When multiple threads or processes access shared
resources (like variables, data structures, or files), synchronization
mechanisms are needed to ensure data consistency and avoid conflicts,
such as race conditions.
➢ Race Condition: A race condition occurs when two or more threads or
processes access shared data concurrently, leading to unpredictable and
erroneous behavior. Proper synchronization can prevent race conditions.
➢ Mutex (Mutual Exclusion): A mutex is a synchronization primitive that
allows only one thread or process to access a shared resource at a time. It
helps prevent race conditions.
➢ Thread Safety: Code is considered thread-safe when it can be safely
executed by multiple threads without causing data corruption or
unexpected behavior. Design patterns and synchronization mechanisms are
used to ensure thread safety.
➢ Deadlock: Deadlock occurs when two or more threads or processes are
unable to proceed because each is waiting for the other to release a
resource. Careful design and resource management are essential to avoid
deadlocks.
➢ Thread Pool: A thread pool is a collection of pre-initialized threads that can
be reused for executing tasks, which helps minimize the overhead of thread
creation and destruction.
➢ Concurrency Control: In database systems, concurrency control
mechanisms ensure that multiple transactions can access and modify the
database concurrently without causing data inconsistencies.
Thread Class in Java
A thread is a program that starts with a method() frequently used in this class only
known as the start() method. This method looks out for the run() method which
is also a method of this class and begins executing the body of the run() method.
Syntax:
public class Thread extends Object implements Runnable
Constructors of this class are as follows:
• Thread():Allocates a new Thread object.
• Thread(Runnable target): Allocates a new Thread object.
• Thread(Runnable target, String name) :Allocates a new Thread object.
• Thread(String name):Allocates a new Thread object.
• Thread(ThreadGroup group, Runnable target):Allocates a new Thread
object.
• Thread(ThreadGroup group, Runnable target, String name):Allocates a
new Thread object so that it has targeted as its run object, has the specified
name as its name, and belongs to the thread group referred to by a group.
• Thread(ThreadGroup group, Runnable target, String name, long
stackSize):Allocates a new Thread object so that it has targeted as its run
object, has the specified name as its name, and belongs to the thread group
referred to by group, and has the specified stack size.
• Thread(ThreadGroup group, String name):Allocates a new Thread object.
Multithreading:
Multithreading is a technique that allows for concurrent (simultaneous) execution
of two or more parts of a program for maximum utilization of a CPU. As a really
basic example, multithreading allows you to write code in one program and listen
to music in another. Programs are made up of processes and threads. You can
think of it like this:
• A program is an executable file like chrome.exe
• A process is an executing instance of a program. When you double click
on the Google Chrome icon on your computer, you start a process which
will run the Google Chrome program.
• Thread is the smallest executable unit of a process. A process can have
multiple threads with one main thread. In the example, a single thread
could be displaying the current tab you’re in, and a different thread could
be another tab.
Example of multithreading
Think about a single processor that is running your IDE. Say you edit one of your
code files and click save. When you click save, it will initiate a workflow which
will cause bytes to be written out to the underlying physical disk. However, IO is
an expensive operation, and the CPU will be idle while bytes are being written
out to the disk.
While IO takes place, the idle CPU could work on something useful and here is
where threads come in - the IO thread is switched out and the UI thread gets
scheduled on the CPU so that if you click elsewhere on the screen, your IDE is
still responsive and does not appear hung or frozen.
Threads can give the illusion of multitasking even though at any given point in
time the CPU is executing only one thread. Each thread gets a slice of time on the
CPU and then gets switched out either.
It initiates a task, which requires waiting and not utilizing the CPU or it completes
its time slot on the CPU. There are many more nuances and intricacies on how
thread scheduling works but this forms the basis of it.
With advances in hardware technology, it is now common to have multi-core
machines. Applications can take advantage of these and have a dedicated CPU
run each thread.
Benefits of multithreading
• Higher throughput, or the ability to process more units of information in a
given amount of time. (This assumes that the throughput ‘cost’ associated
with dealing with multiple threads is lower than the efficiency it creates.
This is usually, but not always, the case.)
• More responsive applications that provide user seamless experiences and
the illusion of multitasking. For example, an app’s UI will still be
functional and responsive even while IO activity is happening in the
background of an image processing app.
• More efficient utilization of resources. Generally speaking, thread creation
is less ‘costly’ compared to creating a brand new process. Web servers that
use threads instead of creating a new process when fielding web requests
consume far fewer resources.
Problems with multithreading
• More difficult to find bugs. The reasons for a process not executing
successfully may now be external to the process itself. The execution order
and prioritization of threads can’t always be predicted and is up to the
operating system itself.
• Higher cost of code maintenance, since the code has now had multiple
levels of complexity added to it.
• More demand on the system. The creation of each thread consumes
additional memory, CPU cycles for book-keeping and time spent on
switching ‘contexts.’ Additionally, keep in mind if a processor is going to
run 5 threads simultaneously it will also need to keep information about
each of those processes around and accessible while the other ones execute,
requiring more registers.
Thread Methods:
What are thread methods in Java?
Thread methods in Java are very important while you're working with a multi-
threaded application. The thread class has some important methods which are
described by the thread itself.
Now let's learn about each of these methods:
1) public void start(): you use this method to start the thread in a separate path
of execution. Then it invokes the run() method on the thread object.
2) public void run(): this method is the starting point of the thread. The
execution of the thread begins from this process.
3) public final void setName(): this method changes the name of the thread
object. There is also a getName() method for retrieving the name of the
current context.
4) public final void setPriority(): you use this method to set the values of the
thread object.
5) public void sleep(): you use this method to suspend the thread for a
particular amount of time.
6) public void interrupt(): you use this method to interrupt a particular thread.
It also causes it to continue execution if it was blocked for any reason.
7) public final boolean isAlive(): this method returns true if the thread is alive.
Applet in Java
An applet is a special kind of Java program that runs in a Java enabled browser.
This is the first Java program that can run over the network using the browser.
Applet is typically embedded inside a web page and runs in the browser.
In other words, we can say that Applets are small Java applications that can be
accessed on an Internet server, transported over Internet, and can be automatically
installed and run as apart of a web document.
After a user receives an applet, the applet can produce a graphical user interface.
It has limited access to resources so that it can run complex computations without
introducing the risk of viruses or breaching data integrity.
To create an applet, a class must class extends java.applet.Applet class.
An Applet class does not have any main() method. It is viewed using JVM. The
JVM can use either a plug-in of the Web browser or a separate runtime
environment to run an applet application.
JVM creates an instance of the applet class and invokes init() method to initialize
an Applet.
Note: Java Applet is deprecated since Java 9. It means Applet API is no longer
considered important.
Program:
import java.awt.*;
import java.applet.*;
public class Simple extends Applet
{
public void paint(Graphics g)
{
g.drawString("A simple Applet", 20, 20);
}
}
Every Applet application must import two packages - java.awt and java.applet.
java.awt.* imports the Abstract Window Toolkit (AWT) classes. Applets interact
with the user (either directly or indirectly) through the AWT. The AWT contains
support for a window-based, graphical user interface. java.applet.* imports the
applet package, which contains the class Applet. Every applet that you create
must be a subclass of Applet class.
The class in the program must be declared as public, because it will be accessed
by code that is outside the program.Every Applet application must declare a
paint() method. This method is defined by AWT class and must be overridden by
the applet. The paint() method is called each time when an applet needs to
redisplay its output. Another important thing to notice about applet application is
that, execution of an applet does not begin at main() method. In fact an applet
application does not have any main() method.
Advantages of Applets
1. It takes very less response time as it works on the client side.
2. It can be run on any browser which has JVM running in it.
param.html
<html>
<applet code=param.class height=300 width=300>
<param Name="pname" value="Welcome to studytonight.com">
</applet>
</html>
The appletviewer runs an applet in the window. It is usually the fastest and easiest
way to test an applet. Create an applet containing the <applet> tag in the
comment, and compile it. It is for testing purposes only.
Using html:
c:\>javac param.java
c:\>appletviewer param.html
Using appletviewer: To run an applet using the appletviewer tool, write in the
command prompt:
c:\>javac First.java
c:\>appletviewer First.java
javac is the compiler that compiles java codes using a command line.
First.java is the applet class to be tested.
appletviewer is a tool that tests the applet class.
Adding image to applet:
/*Java Applet to Load and Display Image*/
import java.awt.*;
import java.applet.*;
public class Load_Image extends Applet
{
Image image;
//Fucntion to Load the image
public void init()
{
image=getImage(getCodeBase(),"logo.jpeg");
}
//Function to draw the image
public void paint(Graphics g)
{
g.drawImage(image,0,0,this);
}
}
/*
<applet code = Load_Image.class width=500 height=500>
</applet>
*/
Program Explanation
1. The method getImage(getCodeBase(),image file name) is used to get the
image.
2. The method drawImage(image file,x,y,component) is used to draw the image
starting from the x and y co-ordinates in the component specified.
The Applet class supplies two getImage() methods:
i. public Image getImage(URL url)
ii. public Image getImage(URL url, String name)
//In a method in an Applet subclass:
Image image1 = getImage(getCodeBase(), "imageFile.gif");
Image image2 = getImage(getDocumentBase(), "anImageFile.jpeg");
Image image3 = getImage(new URL("http://java.sun.com/graphics/people.gif"));
public URL getCodeBase ():
The getCodeBase() method returns the complete URL of the .class file that
contains the applet. This method can be used with the getImage() or the
getAudioClip() methods, described later in this chapter, to load an image or audio
file relative to the .class file location.
public URL getDocumentBase ():
The getDocumentBase() method returns the complete URL of the .html file that
loaded the applet. This can be used with the getImage() or getAudioClip()
methods, described later in this chapter, to load an image or audio file relative to
the .html file.
Swing:
Swing in java is part of Java foundation class which is lightweight and platform
independent. It is used for creating window based applications. It includes
components like button, scroll bar, text field etc. Putting together all these
components makes a graphical user interface.
Swing in Java is a lightweight GUI toolkit which has a wide variety of widgets
for building optimized window based applications. It is a part of the JFC( Java
Foundation Classes). It is build on top of the AWT API and entirely written in
java. It is platform independent unlike AWT and has lightweight components.
It becomes easier to build applications since we already have GUI components
like button, checkbox etc. This is helpful because we do not have to start from the
scratch.
Container Class
Any class which has other components in it is called as a container class. For
building GUI applications at least one container class is necessary.
Following are the three types of container classes:
• Panel – It is used to organize components on to a window
• Frame – A fully functioning window with icons and titles
• Dialog – It is like a pop up window but not fully functional like the frame
JButton Class
It is used to create a labelled button. Using the ActionListener it will result in
some action when the button is pushed. It inherits the AbstractButton class and is
platform independent.
Example:
import javax.swing.*;
public class example{
public static void main(String args[]) {
JFrame a = new JFrame("example");
JButton b = new JButton("click me");
b.setBounds(40,90,85,20);
a.add(b);
a.setSize(300,300);
a.setLayout(null);
a.setVisible(true);
}
}
Layout Manager
To arrange the components inside a container we use the layout manager.
Following are several layout managers:
I. Border layout
II. Flow layout
III. GridBag layout
Border Layout: The default layout manager for every JFrame is BorderLayout. It
places components in upto five places which is top, bottom, left, right and center.
Flow Layout: FlowLayout simply lays the components in a row one after the
other, it is the default layout manager for every JPanel.
GridBag Layout: GridBagLayout places the components in a grid which allows
the components to span more than one cell.
Example: Chat Frame
import javax.swing.*;
import java.awt.*;
class Example {
public static void main(String args[]) {
JFrame frame = new JFrame("Chat Frame");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(400, 400);
JDBC API helps Java applications interact with different databases like MSSQL,
ORACLE, MYSQL, etc. It consists of classes and interfaces of JDBC that allow
the applications to access databases and send requests made by users to the
specified database.
Why JDBC?
Before it was created, we utilized the ODBC API database to connect to the
database and run queries against it. The ODBC API, on the other hand, uses the
ODBC drive in C. Furthermore, it is platform-dependent and unprotected. This is
why Java created the JDBC API, which uses JDBC drivers and is written in the
Java programming language.
Applications of JDBC
JDBC enables you to create Java applications that handle the following three
programming tasks:
• Make a connection to a data source, such as a database.
• Send database queries and update statements.
• Retrieve and process the database results that were returned in response to
your query.
Let’s discuss a real-world example that uses JDBC.
When you search for a movie on a specific date, the database retrieves the number
of tickets available on that day, and if you purchase a ticket, the database is
updated accordingly.
In addition to this domain, JDBC is used in a variety of other fields such as
banking, reservation systems, online retail websites, government portals, and so
on.
It is used in almost every Java programme that connects to an SQL database
management system. Java developers will almost probably utilize JDBC at the
lowest level, regardless of any higher-level libraries, frameworks, object-
relational mappers, or database-access layers they use.
The components of JDBC are listed below. These elements assist us in interacting
with a database. The following are the JDBC components:
1) JDBC Driver Manager: In a JDBC application, the Driver Manager loads
database-specific drivers. This driver manager makes a database
connection. To handle the user request, it additionally makes a database-
specific call to the database.
2) Driver: A driver is an interface that manages database server connectivity.
Communication is handled using DriverManager objects.
3) JDBC-ODBC Bridge Drivers: They are used to link database drivers to the
database. The JDBC method calls are translated into ODBC method calls
by the bridge. To access the ODBC (Open Database Connectivity)
characteristics, it uses the sun.jdbc.odbc package, which includes the
native library.
4) JDBC API: Sun Microsystem has provided JDBC API, which allows you
to write a Java program that talks with any database without modifying the
code. The JDBC API is implemented by the JDBC Driver.
5) JDBC Test Suite: The JDBC Test Suite aids in the testing of JDBC Driver
operations such as insertion, deletion, and updating. It aids in determining
whether or not the JDBC Drivers will run the program. It ensures that the
program will be run by JDBC Drivers with confidence and conformity.
6) Database Server: This is the database server that the JDBC client wants to
communicate with, such as Oracle, MySQL, SQL Server, and so on.
7) Statement: To send SQL statements to the database, you use objects built
using this interface. In addition to performing stored procedures, certainly
derived interfaces accept parameters.
8) RuleSet: These objects retain data retrieved from a database when you use
Statement objects to conduct a SQL query. It functions as an iterator,
allowing you to cycle through the data it contains.
9) SQL Exception: This class is responsible for any errors that occur in a
database application.
Working of JDBC
Java applications need to be programmed for interacting with data sources. JDBC
Drivers for specific databases are to be loaded in a java application for JDBC
support which can be done dynamically at run time. These JDBC drivers
communicate with the respective data source.
Steps to connect a Java program using JDBC API.
1. Load Driver: Load JDBC Driver for specific databases using forName()
method of class Class. Syntax: Class.forName("com.mysql.jdbc.Driver")
2. Create Connection: Create a connection with a database using DriverManager
class. Database credentials are to be passed while establishing the connection.
Syntax: DriverManager.getConnection()
3. Create Query: To manipulate the database we need to create a query using
commands like INSERT, UPDATE, DELETE, etc. These queries are created and
stored in string format. Syntax: String sql_query = "INSERT INTO
Student(name, roll_no) values('ABC','XYZ')"
4. Create Statement: The query we have created is in form of a string. To perform
the operations in the string on a database we need to fire that query on the
database. To achieve this we need to convert a string object into SQL statements.
This can be done using createStatement() and prepareStatement() interfaces.
Syntax: Statement St = con.createStatement();
5. Execute Statement: To execute SQL statements on the database we can use two
methods depending on which type of query we are executing.
• Execute Update: Execute update method is used to execute queries like
insert, update, delete, etc. Return type of executeUpdate() method is int.
Syntax: int check = st.executeUpdate(sql);
• Execute Query: Execute query method is used to execute queries used to
display data from the database, such as select. Return type of
executeQuery() method is result set. Syntax: Resultset =
st.executeUpdate(sql);
6. Closing Statement: After performing operations on the database, it is better to
close every interface object to avoid further conflicts. Synatx: con.close();
Let's see how to connect a Java program using JDBC API.
import java.sql.*;
public class JDBCEx {
public static void main(String args[])
{
Connection con = null;
Statement st = null;
try
{
// Load driver class
Class.forName("com.mysql.jdbc.Driver");
System.out.println("Driver Loaded");
// Obtain a connection
con = DriverManager.getConnection("","","");
System.out.println("Database Connected Successfully!");
//Create Query
String sql = "INSERT INTO Student(sname, scity) values('ABC','Pune')";
// Obtain a statement
st = con.createStatement();
// Execute the query
int check = st.executeUpdate(sql);
if (check > 0)
{
System.out.println("Insert Done");
}
}
catch(Exception e)
{
System.out.println(e);
}
finally
{
//Close Connection
st.close();
con.close();
}
}
}
What Is ODBC?
Open Database Connectivity, commonly known as ODBC, was developed by
Microsoft in 1992. Different applications use it as a general API to access and
manipulate databases. ODBC development used numerous essential
programming languages like Java, Perl, and C# to ensure broad usability across
other platforms.
Since the platform used is Windows, it is program based. It provides a standard
for businesses and developers to access databases. The latest version of ODBC is
Version 17.10.3, released on January 26, 2023. For example, Microsoft Office
supports ODBC.
Advantages of JDBC
a) Pure Java: It is purely dedicated to Java. It can work on any platform which
supports Java Programming language.
b) Better performance : It performs better than ODBC in some cases. It can
reuse the used statements and support batch updates.
c) Object-oriented: Since it is Object Oriented, it enables it to work with Java
more easily.
d) Standardized : JDBC is a standard API that supports all major relational
databases.
Disadvantages of JDBC
1) Complexity: JDBC is more complex to use than ODBC. It needs to manage
the database manually.
2) Limited Functionality: Less functionality than other APIs like JPA or
Hibernate, which provide a higher level of abstraction.
3) Platform-specific Driver: It is platform-specific. It can work on any
platform which supports Java Programming language.
Advantages of ODBC
a) Cross-Platform : ODBC works on multiple platforms like Linux, Windows,
and Linux.
b) Compatibility : ODBC provides compatibility with different data sources
like relational databases, files, etc.
c) Support for non-Java languages : ODBC supports Java and different
languages like C, C++, C#, Perl, etc.
d) Widely used : Since it is more flexible and compatible with other
languages, that make it such a widely used API.
Disadvantages of ODBC
1. Performance: ODBC is much slower than JDBC since it has an additional
layer for abstraction.
2. Complicated to construct: ODBC drivers are difficult to create and
maintain.
3. Slow with Large databases: It can not handle large databases like JDBC.
However, it is easy to use.
4. Does not provide standardized: ODBC needs to be sufficiently
standardized as it is mainly used by clients
JDBC Drivers: JDBC drivers are client-side adapters (installed on the client
machine, not on the server) that convert requests from Java programs to a protocol
that the DBMS can understand. There are 4 types of JDBC drivers:
• Type-1 driver or JDBC-ODBC bridge driver
• Type-2 driver or Native-API driver
• Type-3 driver or Network Protocol driver
• Type-4 driver or Thin driver
Type-1 driver : Type-1 driver or JDBC-ODBC bridge driver uses ODBC driver
to connect to the database. The JDBC-ODBC bridge driver converts JDBC
method calls into the ODBC function calls. Type-1 driver is also called Universal
driver because it can be used to connect to any of the databases.
➢ As a common driver is used in order to interact with different databases,
the data transferred through this driver is not so secured.
➢ The ODBC bridge driver is needed to be installed in individual client
machines.
➢ Type-1 driver isn’t written in java, that’s why it isn’t a portable driver.
➢ This driver software is built-in with JDK so no need to install separately.
➢ It is a database independent driver.
Type-2 driver : The Native API driver uses the client -side libraries of the
database. This driver converts JDBC method calls into native calls of the database
API. In order to interact with different database, this driver needs their local API,
that’s why data transfer is much more secure as compared to type-1 driver.
➢ Driver needs to be installed separately in individual client machines
➢ The Vendor client library needs to be installed on client machine.
➢ Type-2 driver isn’t written in java, that’s why it isn’t a portable driver
➢ It is a database dependent driver.
Type-3 driver : The Network Protocol driver uses middleware (application server)
that converts JDBC calls directly or indirectly into the vendor-specific database
protocol. Here all the database connectivity drivers are present in a single server,
hence no need of individual client-side installation.
➢ Type-3 drivers are fully written in Java, hence they are portable drivers.
➢ No client side library is required because of application server that can
perform many tasks like auditing, load balancing, logging etc.
➢ Network support is required on client machine.
➢ Maintenance of Network Protocol driver becomes costly because it
requires database-specific coding to be done in the middle tier.
➢ Switch facility to switch over from one database to another database.
Type-4 driver : Type-4 driver is also called native protocol driver. This driver
interact directly with database. It does not require any native database library, that
is why it is also known as Thin Driver.
➢ Does not require any native library and Middleware server, so no client-
side or server-side installation.
➢ It is fully written in Java language, hence they are portable drivers.