You are on page 1of 24

Advanced Java

*Each Question 2 Marks


1. Write down 2 methods of connection interface.
1)JDBC (Java Database Connectivity): JDBC is a Java-based API that
allows Java applications to interact with relational databases. It provides
a set of classes and interfaces to connect to a database, send SQL
queries, and retrieve results. The key interface in JDBC is
java.sql.Connection, which represents a connection to a database.
Developers use this interface to establish a connection, create
statements, and manage transactions.
2)Socket Programming Interface: In advanced Java, you may also
encounter network-related interfaces for socket programming. Java
provides classes and interfaces in the java.net package for network
communication. The java.net.Socket class is commonly used to create
client sockets, and the java.net.ServerSocket class is used for server
sockets.

2. What is sleep() method in multithreading.


In Java multithreading, the sleep() method is a static method provided
by the Thread class. This method is used to temporarily pause the
execution of the current thread for a specified amount of time. When a
thread invokes the sleep() method, it enters into a "timed waiting" state
for the specified duration

3. What is the method to set the thread priority.


Setting thread priority is often done in programming when working with
multithreaded applications. The method to set thread priority can vary
depending on the programming language and platform you are using. I'll
provide a general overview, but you should refer to the documentation
of the specific language and platform you are working with for detailed
information.

Java (using Thread class):


In Java, you can set thread priority using the setPriority method of the
Thread class. The thread priority is an integer value ranging from
Thread.MIN_PRIORITY to Thread.MAX_PRIORITY.
java
Thread thread = new Thread();
thread.setPriority(Thread.NORM_PRIORITY); // or use
Thread.MIN_PRIORITY, Thread.MAX_PRIORITY

4. Write down 2 classes used in socket programming.


In Java, the ServerSocket and Socket classes from the java.net package
are commonly used for socket programming. Here's a brief overview of
each:

1)ServerSocket Class:
The ServerSocket class is used to create a server-side socket. It listens for
incoming client connections and, upon accepting a connection, returns a
Socket object through which communication with the client occurs.
2)Socket Class:
The Socket class represents a client-side socket. It is used to establish a
connection to a server's ServerSocket and provides input and output
streams for communication with the server.

5. What is IP address.
An IP (Internet Protocol) address is a numerical label assigned to each
device connected to a computer network that uses the Internet Protocol
for communication. IP addresses serve two main purposes: host or
network interface identification and location addressing. There are two
types of IP addresses, IPv4 and IPv6, which differ in their address
formats.

6. What is doGet () method of servlet?


Java servlets, the doGet() method is one of the standard HTTP request-
handling methods provided by the HttpServlet class. Servlets are Java
classes that extend the HttpServlet class to handle HTTP requests and
generate responses. The doGet() method is invoked when a client sends
an HTTP GET request to the servlet.

7. What are the parameters of service() method of servlet.


The service() method is a fundamental method in Java servlets. It is
defined in the javax.servlet.Servlet interface, and the HttpServlet class,
which is commonly extended by servlets, provides an implementation
for it. The service() method is responsible for handling requests from
clients.
void service(ServletRequest req, ServletResponse res) throws
ServletException, IOException;
Parameters:
1)ServletRequest req:
This parameter represents the client's request. It is an object of type
ServletRequest, and it contains information about the client's request,
such as parameters, headers, and other details.

2)ServletResponse res:
This parameter represents the response that the servlet will send back
to the client. It is an object of type ServletResponse, and it allows the
servlet to construct and send the response to the client.

3)throws ServletException:
This exception is thrown to indicate that the servlet encountered a
servlet-specific problem. It is a checked exception, and servlets are
expected to catch or propagate it.

4)throws IOException:
This exception is thrown if an input or output error occurs while the
servlet is handling the request. Like ServletException, it is a checked
exception.

8. What is JSP?
JSP, or JavaServer Pages, is a technology used in Java web development
to create dynamic web pages. It is a technology that allows developers
to embed Java code into HTML pages, providing a way to separate the
presentation logic from the business logic in a web application.

9. What is Hibernate?
Hibernate is an open-source object-relational mapping (ORM)
framework for Java. It provides a framework for mapping Java objects to
relational database tables and vice versa. The primary goal of Hibernate
is to simplify the process of database interactions in Java applications by
providing a high-level, object-oriented API for data persistence.

10.What is getConnection method?


The getConnection method is a method commonly used in Java for
establishing a connection to a relational database. It is part of the JDBC
(Java Database Connectivity) API, which is a Java-based framework that
provides a standard interface for connecting Java applications to
relational databases.

The getConnection method is typically provided by a JDBC DataSource or


by the DriverManager class. Its purpose is to create a connection to a
specific database using connection parameters such as the database
URL, username, and password.

*Each Question 4 Marks


1. What is statement? Explain the types of statements in JDBC.
In JDBC (Java Database Connectivity), a statement is an interface
provided by the JDBC API that allows Java applications to interact with a
database. A statement is used to execute SQL queries, updates, and
other SQL commands against a database. The Statement interface is part
of the java.sql package.

There are three main types of statements in JDBC:


1)Statement:
The Statement interface is the simplest form of a SQL statement. It is
used for executing static SQL queries without parameters. However, it is
susceptible to SQL injection attacks when incorporating user input into
the SQL query.
Statement statement = connection.createStatement();
ResultSet resultSet = statement.executeQuery("SELECT * FROM
my_table");

2)PreparedStatement:
The PreparedStatement interface extends Statement and provides a way
to execute precompiled SQL queries with parameters. It is more efficient
than a regular Statement for executing the same SQL query multiple
times, as the SQL query is compiled only once.
String sql = "INSERT INTO my_table (column1, column2) VALUES
(?, ?)";
PreparedStatement preparedStatement =
connection.prepareStatement(sql);
preparedStatement.setString(1, "value1");
preparedStatement.setString(2, "value2");
int rowCount = preparedStatement.executeUpdate();
The use of placeholders (?) allows for better security against SQL
injection, as values are bound to the prepared statement rather than
concatenated directly into the SQL query.

3)CallableStatement:
The CallableStatement interface extends PreparedStatement and is used
to execute stored procedures in the database. It can also be used for
executing dynamic SQL commands.
String sql = "{CALL my_procedure(?, ?)}";
CallableStatement callableStatement = connection.prepareCall(sql);
callableStatement.setInt(1, 123);
callableStatement.setString(2, "parameter2");
boolean results = callableStatement.execute();
CallableStatement is particularly useful when working with database
stored procedures.
2. Explain thread life cycle with diagram.

The thread life cycle in Java refers to the different states a thread can be
in during its lifetime. The life cycle of a thread is represented by a set of
states through which a thread transitions. Here is a general
representation of the thread life cycle along with a diagram:

Thread States:
1)New:
A thread is in the new state when an instance of the Thread class is
created but before the start() method is invoked. In this state, the
thread is not yet eligible for execution.

2)Runnable:
A thread transitions to the runnable state when the start() method is
called. The thread is now ready to run and waiting for the CPU to be
allocated.

3)Blocked:
A thread becomes blocked when it is waiting for a monitor lock to enter
a synchronized block/method or waiting for an I/O operation to
complete. In this state, the thread is temporarily inactive.

4)Waiting:
A thread transitions to the waiting state when it is waiting indefinitely
for another thread to perform a particular action. The thread remains in
this state until it is explicitly notified or interrupted.

5)Timed Waiting:
Similar to the waiting state, a thread enters the timed waiting state
when it is waiting for another thread but for a specified period. The
thread will exit this state when the specified time elapses or when it is
explicitly notified/interrupted.

6)Terminated:
A thread enters the terminated state when its run() method completes
or when the stop() method is called. A terminated thread cannot be
restarted.

3. What are the implicit objects in JSP. Explain any 4.


In JSP (JavaServer Pages), implicit objects are Java objects that are
automatically available and can be used without being explicitly declared
or instantiated in the JSP page. These objects provide access to various
aspects of the JSP environment, such as request, response, session, and
application information. Here are four commonly used implicit objects in
JSP:

1)request Object:
The request object represents the client's request to the server. It is an
instance of the HttpServletRequest class and provides information about
the client's request, including parameters, headers, and other details.
<%
String parameterValue = request.getParameter("paramName");
%>

2)response Object:
The response object represents the server's response to the client. It is
an instance of the HttpServletResponse class and is used to manipulate
the response, set headers, and send content back to the client.
<%
response.setContentType("text/html");
response.getWriter().println("Hello, World!");
%>

3)session Object:
The session object represents the user's session and is an instance of the
HttpSession class. It allows for the storage of user-specific information
that persists across multiple requests from the same client.
<%
session.setAttribute("username", "john_doe");
%>

4)application Object:
The application object represents the entire web application and is an
instance of the ServletContext class. It allows for the storage of
information that is shared among all users of the application.
<%
application.setAttribute("appVariable", "shared_value");
%>

4. Write down the difference between doGet() and doPost()method.


5. Write a java program to count number of records in a table.
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

public class RecordCounter {

public static void main(String[] args) {


// Database connection parameters
String url = "jdbc:mysql://localhost:3306/your_database";
String username = "your_username";
String password = "your_password";

// SQL query to count records


String sql = "SELECT COUNT(*) AS recordCount FROM
example_table";

try (Connection connection = DriverManager.getConnection(url,


username, password);
PreparedStatement preparedStatement =
connection.prepareStatement(sql);
ResultSet resultSet = preparedStatement.executeQuery()) {

// Check if there is a result


if (resultSet.next()) {
int recordCount = resultSet.getInt("recordCount");
System.out.println("Number of records in the table: " +
recordCount);
}

} catch (SQLException e) {
e.printStackTrace();
}
}
}
6. Explain Architecture of Hibernate.
Hibernate is an open-source framework for Java that provides an object-
relational mapping (ORM) solution. It simplifies the development of
database interactions by allowing developers to work with Java objects
instead of SQL queries. The architecture of Hibernate is designed to
handle the mapping between Java objects and database tables,
providing a convenient way to perform database operations.

The architecture of Hibernate can be explained in several key


components:
1)Configuration:
hibernate.cfg.xml: This XML file is used for configuring Hibernate
settings. It contains information about the database connection
properties, dialect (database-specific SQL variations), and other
configuration details.

2)SessionFactory:
The SessionFactory is a heavyweight object that is created only once in
the application. It serves as a factory for Session objects.
Configuration: The SessionFactory is configured using the information
provided in the hibernate.cfg.xml file or through programmatically
setting properties.

3)Session:
A Session is a lightweight, short-lived object representing a single-
threaded unit of work. It is created by the SessionFactory and is used to
perform database operations.
Persistence Context: The Session acts as a first-level cache and maintains
the persistence context. It keeps track of all the objects loaded from the
database during its lifetime.

4)Transaction:
Hibernate supports transactions, and a transaction is typically initiated
using the Transaction interface. Transactions ensure that a group of
operations are treated as a single unit of work, and they are either
committed or rolled back as a whole.
5)Mapping Files:
Hibernate uses XML or annotations to define the mapping between Java
objects and database tables. These mapping files specify how the
properties of Java objects are mapped to the columns of database
tables.

6)POJO (Plain Old Java Object):


The Java objects that are persisted using Hibernate are referred to as
POJOs. These are simple Java classes that do not depend on any special
framework interfaces or base classes.

7)Query Language (HQL):


Hibernate provides its own query language called Hibernate Query
Language (HQL), which is similar to SQL but operates on the Java objects
instead of database tables. HQL allows developers to express queries in
a more object-oriented manner.

8)Caching:
Hibernate supports caching mechanisms to improve performance. It
includes first-level cache (associated with a Session) and second-level
cache (shared among multiple Session instances).

9)Transaction Management:
Hibernate supports both programmatic and declarative transaction
management. Developers can explicitly manage transactions using the
Transaction API, or they can rely on container-managed transactions in a
Java EE environment.

7. What is Result set interface in JDBC? Explain methods in Resultset


interface.
In JDBC (Java Database Connectivity), the ResultSet interface is a part of
the java.sql package and provides methods for retrieving and manipulating
the results of a database query. When you execute a SQL query using a
Statement object, the result is typically returned as a ResultSet object. The
ResultSet interface represents a table of data resulting from a database
query.
Here are some of the key methods in the ResultSet interface:
1)Navigation Methods:
boolean next(): Moves the cursor to the next row in the ResultSet. Returns
true if the next row exists; otherwise, returns false.
boolean previous(): Moves the cursor to the previous row in the ResultSet.
Returns true if the previous row exists; otherwise, returns false.
boolean first(): Moves the cursor to the first row in the ResultSet.
boolean last(): Moves the cursor to the last row in the ResultSet.
boolean absolute(int row): Moves the cursor to the specified row number.
Returns true if the cursor is moved to the specified row; otherwise, returns
false.

2)Data Retrieval Methods:


int getInt(int columnIndex): Retrieves the value of the specified column as
an int.
String getString(int columnIndex): Retrieves the value of the specified
column as a String.
double getDouble(int columnIndex): Retrieves the value of the specified
column as a double.
Object getObject(int columnIndex): Retrieves the value of the specified
column as an Object.
Similar methods are available for other data types such as boolean, long,
Date, etc.

3)Column Label Retrieval Methods:


Similar to the methods mentioned above, but these methods take a column
label as an argument instead of an index. For example: getInt(String
columnLabel), getString(String columnLabel), etc.

4)Metadata Retrieval Methods:


int getMetaData(): Returns the ResultSetMetaData object, which contains
information about the columns of the ResultSet.
int getColumnCount(): Returns the number of columns in the ResultSet.
5)Updating Data Methods:
void updateInt(int columnIndex, int value): Updates the value of the
specified column with the given int value.
void updateString(int columnIndex, String value): Updates the value of the
specified column with the given String value.
Similar methods are available for other data types.

6)Cursor and Positioning Methods:


void beforeFirst(): Moves the cursor to before the first row.
void afterLast(): Moves the cursor to after the last row.
void moveToInsertRow(): Moves the cursor to the insert row. Used for
inserting new rows.
void moveToCurrentRow(): Moves the cursor back to the current row.

8. Explain JSP life cycle with diagram.


JavaServer Pages (JSP) have a well-defined life cycle that involves several
phases, including translation, compilation, initialization, execution, and
destruction. Here is an explanation of the JSP life cycle along with a
simplified diagram:

JSP Life Cycle Phases:


1)Translation Phase:
JSP Page (.jsp): The JSP page is written with a mix of HTML and Java
code.
Translation: When a client (browser) requests the JSP page for the first
time, the JSP container translates the JSP page into a servlet class.
Servlet Class (.java): The translated servlet class extends HttpServlet and
contains the equivalent Java code for the JSP page.

2)Compilation Phase:
Compilation: The servlet class is compiled into bytecode by the Java
compiler.
Servlet Class (.class): The compiled servlet class is loaded by the class
loader.
3)Initialization Phase:
Instantiation: An instance of the servlet class is created by the servlet
container.
Initialization: The init() method of the servlet is called. Developers can
override this method to perform any initialization tasks.

4)Request Handling (Execution) Phase:


Request Processing: For each client request, the service() method is
invoked by the servlet container.
Service Method: The service() method handles the request, generating
dynamic content by executing the Java code in the JSP page.

5)Destroy Phase:
Destruction: When the servlet container decides to take the servlet out
of service (e.g., during shutdown), the destroy() method is called.
Cleanup: Developers can override the destroy() method to release
resources and perform cleanup tasks.

9. Write a java program in to print from 100 to 1. (use sleep() method)


public class CountDownWithSleep {
public static void main(String[] args) {
try {
// Start counting down from 100
for (int i = 100; i >= 1; i--) {
System.out.println(i);

// Pause for 100 milliseconds (0.1 seconds)


Thread.sleep(100);
}
} catch (InterruptedException e) {
// Handle the exception if sleep is interrupted
e.printStackTrace();
}
}
}
10.Write a java program to create table student with attributes Rno, Sname,
Per.
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;

public class CreateTableStudent {


// JDBC URL, username, and password of MySQL server
private static final String JDBC_URL =
"jdbc:mysql://localhost:3306/your_database_name";
private static final String USERNAME = "your_username";
private static final String PASSWORD = "your_password";

public static void main(String[] args) {


// SQL statement to create the "student" table
String createTableSQL = "CREATE TABLE student ("
+ "Rno INT PRIMARY KEY,"
+ "Sname VARCHAR(255),"
+ "Per DOUBLE)";

try (
// Establish a connection to the database
Connection connection =
DriverManager.getConnection(JDBC_URL, USERNAME, PASSWORD);

// Create a statement
Statement statement = connection.createStatement()
){
// Execute the SQL statement to create the "student" table
statement.executeUpdate(createTableSQL);

System.out.println("Table 'student' created successfully.");

} catch (SQLException e) {
e.printStackTrace();
}
}
}

11.What are the states of the object in hibernate?


an object goes through different states during its lifecycle as it interacts
with the database. These states are defined by the Hibernate framework,
and they are crucial for managing the persistence of objects. The various
states of an object in Hibernate are:

1)Transient (New) State:


An object is in a transient state if it has just been instantiated using the new
keyword, and it is not associated with any Hibernate Session.
It doesn't have a database identity, and changes made to the object are not
reflected in the database.

2)Persistent State:
An object enters the persistent state when it is associated with a Hibernate
Session.
In this state, any changes made to the object are tracked by the Hibernate
framework, and these changes can be synchronized with the database.

3)Detached State:
An object becomes detached when it was previously associated with a
Session, but the Session is closed or the object is explicitly evicted from the
Session.
In the detached state, the object is no longer associated with a specific
Hibernate Session. Modifications to the object do not get automatically
synchronized with the database.

4)Removed (Deleted) State:


An object is in the removed state when it was previously persistent but has
been deleted from the database using the delete() method.
After deletion, the object becomes detached, and any further changes to it
will not affect the database.
12.What is session tracking? What are the different ways of session tracking
in servlet.
Session tracking in the context of web development refers to the
mechanism used to maintain state and identify a user across multiple
requests and responses between a web client (typically a browser) and a
web server. Since HTTP, the underlying protocol of the World Wide Web, is
stateless, session tracking is necessary to associate multiple requests from
the same user as part of a single logical session.

In Java servlets, there are several ways to perform session tracking:


1)Cookies:
Cookies are small pieces of data sent by the server and stored on the
client's machine.
Servlets can use cookies to store a unique identifier (session ID) on the
client side, which is sent with each subsequent request.
Java Servlet API provides the HttpServletResponse and HttpServletRequest
classes to work with cookies.

2)URL Rewriting:
In URL rewriting, the session ID is appended to every URL link on a web
page.
This is done by the server, which embeds the session ID as a parameter in
the URL.
This method is transparent to the user but may expose session information
in the URL.

3)Hidden Form Fields:


The server can include a hidden form field in an HTML form, which contains
the session ID.
When the form is submitted, the session ID is sent back to the server along
with other form data.

4)URL Encoding:
Similar to URL rewriting, but instead of appending the session ID as a
parameter, it is included in the URL path.
This method can be less visible to users compared to URL rewriting.
5)HTTP Session Object:
Servlets can use the HttpSession object to store user-specific information.
The server generates a unique session ID, which is then used to associate
subsequent requests with the same session.
The session data is stored on the server side, and the client receives a
cookie or URL parameter containing the session ID.

13.What is thread Priority? How to set the thread priorities?


Thread priority in Java is a way to indicate the importance or urgency of a
thread relative to other threads in the same process. Each thread in Java is
assigned a priority that influences the order in which threads are scheduled
to run by the thread scheduler. Thread priority is an integer value, and the
default priority is typically set to the normal priority.

Thread priorities in Java are represented by the following constants in the


Thread class:
Thread.MIN_PRIORITY (1): The minimum priority.
Thread.NORM_PRIORITY (5): The default or normal priority.
Thread.MAX_PRIORITY (10): The maximum priority.
To set the priority of a thread, you can use the setPriority(int priority)
method, which is part of the Thread class. The priority should be an integer
value within the range specified by Thread.MIN_PRIORITY and

Thread.MAX_PRIORITY. For example:


Thread myThread = new MyThread();
myThread.setPriority(Thread.MIN_PRIORITY); // Setting minimum priority

It's important to note that the actual behavior of thread priorities can vary
across different Java Virtual Machine (JVM) implementations and operating
systems. While the priority mechanism is a hint to the thread scheduler, the
scheduler is not obligated to strictly adhere to these priorities.
14.Write a JSP application to accept a user name and greet the user.
<!DOCTYPE html>
<html>
<head>
<title>Greet User</title>
</head>
<body>
<h2>Greet User</h2>

<%-- Check if the user has submitted the form --%>


<%
String userName = request.getParameter("userName");

if (userName != null && !userName.isEmpty()) {


%>
<p>Hello, <%= userName %>! Welcome to our website.</p>
<%
} else {
%>
<form action="greetUser.jsp" method="post">
Enter your name: <input type="text" name="userName" />
<input type="submit" value="Submit" />
</form>
<%
}
%>

</body>
</html>

15.Write a java program to display IP address of a machine.


import java.net.InetAddress;
import java.net.UnknownHostException;

public class IPAddressExample {


public static void main(String[] args) {
try {
// Get the local host
InetAddress localhost = InetAddress.getLocalHost();

// Display the IP address


System.out.println("IP Address of the local machine: " +
localhost.getHostAddress());
} catch (UnknownHostException e) {
e.printStackTrace();
}
}
}

*Each Question 4 Marks


1. Connection interface.
In Java, the Connection interface is part of the JDBC (Java Database
Connectivity) API. JDBC is a Java-based API that provides a standard
interface for connecting to relational databases and executing SQL
queries. The Connection interface is a fundamental part of JDBC and
represents a connection to a database.
Here are some key points about the Connection interface:
1)Package:
The Connection interface is part of the java.sql package.

2)Acquiring a Connection:
Instances of the Connection interface are typically obtained using a
DriverManager by specifying the URL of the database, as well as the
username and password.
Connection connection =
DriverManager.getConnection("jdbc:database_url", "username",
"password");

3)Methods:
The Connection interface provides various methods for interacting with
the database, including methods for creating statements, committing or
rolling back transactions, closing the connection, and obtaining
metadata about the database.
Statement statement = connection.createStatement();
ResultSet resultSet = statement.executeQuery("SELECT * FROM
my_table");
// ... process the result set
connection.close();

4)Transaction Management:
The Connection interface is involved in managing database transactions.
You can commit transactions using the commit() method or rollback
changes using the rollback() method.
try {
connection.setAutoCommit(false);
// Perform database operations
connection.commit();
} catch (SQLException e) {
connection.rollback();
} finally {
connection.setAutoCommit(true);
}

5)Closing the Connection:


It's important to close the Connection when it's no longer needed to
release resources and avoid potential memory leaks.
connection.close();

The Connection interface plays a crucial role in database interactions


using JDBC. It encapsulates the connection to the database and provides
methods for performing various database operations. It's important to
handle exceptions that may occur during database interactions and to
close the connection properly to ensure resource cleanup.

2. Runnable interface.
The Runnable interface is a fundamental interface in Java that is part of
the java.lang package. It is primarily used for defining objects whose
instances are intended to be executed by a thread. Objects that
implement the Runnable interface represent tasks that can be run
concurrently in a separate thread.
The Runnable interface has a single abstract method named run(), which
is where the code for the concurrent task should be placed. When a
class implements Runnable, its instances can be passed to a Thread
constructor, and the run() method will be executed when the thread
starts.

3. Thread synchronization.
Thread synchronization is the process of controlling the execution of
threads to ensure that they don't interfere with each other, especially
when they share resources or data. In a multithreaded environment,
without proper synchronization, concurrent access to shared resources
can lead to data corruption, inconsistencies, and other unexpected
behavior. Java provides several mechanisms for thread synchronization:

1)Synchronized Methods:
You can use the synchronized keyword to declare a method as
synchronized. When a thread invokes a synchronized method, it locks
the object's monitor (or intrinsic lock) and ensures that only one thread
can execute the synchronized method at a time.
public synchronized void synchronizedMethod() {
// Synchronized code block
// ...
}

2)Synchronized Blocks:
You can use synchronized blocks to explicitly specify which part of the
code should be synchronized. This allows for more fine-grained control
over synchronization.
public void someMethod() {
// Non-critical section code

synchronized (lockObject) {
// Synchronized code block
// Only one thread can execute this block at a time
// ...
}
// Non-critical section code
}

3)Reentrant Synchronization:
Java supports reentrant synchronization, which means that a thread can
acquire the same lock multiple times without blocking itself. This is
useful when a method calls another method that requires the same lock.

4)Volatile Keyword:
The volatile keyword can be used to declare a variable as volatile.
Accessing a volatile variable guarantees that any thread reading the
variable sees the most recent modification made by any other thread.
However, it does not provide atomicity for compound operations.
private volatile int sharedVariable;

5)Locks (java.util.concurrent.locks):
Java provides a more flexible and powerful mechanism for
synchronization using explicit locks from the java.util.concurrent.locks
package, such as ReentrantLock. These locks offer more control over
locking and unlocking compared to synchronized methods and blocks.

ReentrantLock lock = new ReentrantLock();

public void someMethod() {


lock.lock();
try {
// Critical section code
// ...
} finally {
lock.unlock();
}
}
Atomic Classes (java.util.concurrent.atomic):

The java.util.concurrent.atomic package provides atomic classes like


AtomicInteger, AtomicLong, etc., which offer atomic operations without
the need for explicit synchronization.
private AtomicInteger atomicCounter = new AtomicInteger(0);

public void incrementCounter() {


atomicCounter.incrementAndGet();
}

You might also like