Threads are lightweight processes as the overhead of switching between threads is less
Synchronization allows only one thread to perform an operation on a object at a time.
Synchronization prevent data corruption
Thread Synchronization-The synchronized methods define critical sections.
You will learn the Deadlock Condition in Threads and Syncronization of Threads
This talk was given in ilJUG on the 29th of July 2014 and discusses the new Java8 StampedLock class. It compares it to different locking mechanism is Java and shows some insights deduced from a simple benchmark
Java has a solid Memory Model, and there are a couple of excellent libraries for concurrency. When you start working with threads however, pitfalls start appearing - especially if the program is supposed to be fast and correct. This session shows proven solutions for some typical problems, showing how to view program code from a concurrency perspective: Which threads share which data, and how? How to reduce the impact of locks? How to avoid them altogether - and when is that worth it?
This talk was given in ilJUG on the 29th of July 2014 and discusses the new Java8 StampedLock class. It compares it to different locking mechanism is Java and shows some insights deduced from a simple benchmark
Java has a solid Memory Model, and there are a couple of excellent libraries for concurrency. When you start working with threads however, pitfalls start appearing - especially if the program is supposed to be fast and correct. This session shows proven solutions for some typical problems, showing how to view program code from a concurrency perspective: Which threads share which data, and how? How to reduce the impact of locks? How to avoid them altogether - and when is that worth it?
This session discusses about the basic building blocks of Concurrent Programming in Java, which include:
synchronisation part 2, synchronized methods, intrinsic locks, atomic access, liveness, deadlock, starvation, livelock, guarded blocks, immutable objects, synchronized class example, strategy for defining immutable objects
Advanced Introduction to Java Multi-Threading - Full (chok)choksheak
Designed for the beginning Java developer to grasp advanced Java multi-threading concepts quickly. Talks mainly about the Java Memory Model and the Concurrent Utilities. This presentation is Java-specific and we intentionally omit general non-Java-specific details, such as hardware architecture, OS, native threads, algorithms, and general software design principles etc.
This session discusses about the basic building blocks of Concurrent Programming in Java, which include:
high-level concurrency objects, lock objects, executors, executor interfaces, thread pools, fork/join, concurrent collections, atomic variables, concurrent random numbers.
This presentation is about advanced multithreading and concurrency in Java. I have tried my best to explain the concepts with code. Feel free to reach me if you have any questions or concerns.
Concurrency Programming in Java - 05 - Processes and Threads, Thread Objects,...Sachintha Gunasena
This session discusses about the basic building blocks of Concurrent Programming in Java, which include:
processes, threads, how to define a thread, how to start a thread, how to sleep a thread, thread interrupt, interrupt status flag, joins, simple thread example, synchronization part 1, thread interference, memory consistency errors
Threads And Synchronization in C#
Concept about Threads And Synchronization in C#
it will help you about this concept
feel free
Download free programming applications on
http://www.androidapplications.xyz
In 5-2020, I and Minh have a sharing session about Sync, Async, and Multi-threading in C#.
We believe this is one of the most important things when working with .Net technology.
This sharing is aiming to Junior Dev, or even Sr Dev or anyone interested in Sync, Async, and Multi-threading.
I hope it will bring you some values.
This session discusses about the basic building blocks of Concurrent Programming in Java, which include:
synchronisation part 2, synchronized methods, intrinsic locks, atomic access, liveness, deadlock, starvation, livelock, guarded blocks, immutable objects, synchronized class example, strategy for defining immutable objects
Advanced Introduction to Java Multi-Threading - Full (chok)choksheak
Designed for the beginning Java developer to grasp advanced Java multi-threading concepts quickly. Talks mainly about the Java Memory Model and the Concurrent Utilities. This presentation is Java-specific and we intentionally omit general non-Java-specific details, such as hardware architecture, OS, native threads, algorithms, and general software design principles etc.
This session discusses about the basic building blocks of Concurrent Programming in Java, which include:
high-level concurrency objects, lock objects, executors, executor interfaces, thread pools, fork/join, concurrent collections, atomic variables, concurrent random numbers.
This presentation is about advanced multithreading and concurrency in Java. I have tried my best to explain the concepts with code. Feel free to reach me if you have any questions or concerns.
Concurrency Programming in Java - 05 - Processes and Threads, Thread Objects,...Sachintha Gunasena
This session discusses about the basic building blocks of Concurrent Programming in Java, which include:
processes, threads, how to define a thread, how to start a thread, how to sleep a thread, thread interrupt, interrupt status flag, joins, simple thread example, synchronization part 1, thread interference, memory consistency errors
Threads And Synchronization in C#
Concept about Threads And Synchronization in C#
it will help you about this concept
feel free
Download free programming applications on
http://www.androidapplications.xyz
In 5-2020, I and Minh have a sharing session about Sync, Async, and Multi-threading in C#.
We believe this is one of the most important things when working with .Net technology.
This sharing is aiming to Junior Dev, or even Sr Dev or anyone interested in Sync, Async, and Multi-threading.
I hope it will bring you some values.
In this session you will learn:
Threads
For more information, visit this link: https://www.mindsmapped.com/courses/software-development/online-java-training-for-beginners/
JAVA CERTIFICATION EXAM OBJECTIVES
COVERED IN THIS CHAPTER:
4.1 Write code to define, instantiate, and start new threads
using both java.lang.Thread and java.lang.Runnable.
4.2 Recognize the states in which a thread can exist, and
identify ways in which a thread can transition from one state
to another.
4.3 Given a scenario, write code that makes appropriate use
of object locking to protect static or instance variables from
concurrent access problems.
4.4 Given a scenario, write code that makes appropriate use of wait, notify, or notifyAll.
Multithreaded fundamentals
The thread class and runnable interface
Creating a thread
Creating multiple threads
Determining when a thread ends
Thread priorities
Synchronization
Using synchronized methods
The synchronized statement
Thread communication using notify(), wait() and notifyall()
Suspending , resuming and stopping threads
Water scarcity is the lack of fresh water resources to meet the standard water demand. There are two type of water scarcity. One is physical. The other is economic water scarcity.
Explore the innovative world of trenchless pipe repair with our comprehensive guide, "The Benefits and Techniques of Trenchless Pipe Repair." This document delves into the modern methods of repairing underground pipes without the need for extensive excavation, highlighting the numerous advantages and the latest techniques used in the industry.
Learn about the cost savings, reduced environmental impact, and minimal disruption associated with trenchless technology. Discover detailed explanations of popular techniques such as pipe bursting, cured-in-place pipe (CIPP) lining, and directional drilling. Understand how these methods can be applied to various types of infrastructure, from residential plumbing to large-scale municipal systems.
Ideal for homeowners, contractors, engineers, and anyone interested in modern plumbing solutions, this guide provides valuable insights into why trenchless pipe repair is becoming the preferred choice for pipe rehabilitation. Stay informed about the latest advancements and best practices in the field.
Saudi Arabia stands as a titan in the global energy landscape, renowned for its abundant oil and gas resources. It's the largest exporter of petroleum and holds some of the world's most significant reserves. Let's delve into the top 10 oil and gas projects shaping Saudi Arabia's energy future in 2024.
Industrial Training at Shahjalal Fertilizer Company Limited (SFCL)MdTanvirMahtab2
This presentation is about the working procedure of Shahjalal Fertilizer Company Limited (SFCL). A Govt. owned Company of Bangladesh Chemical Industries Corporation under Ministry of Industries.
Final project report on grocery store management system..pdfKamal Acharya
In today’s fast-changing business environment, it’s extremely important to be able to respond to client needs in the most effective and timely manner. If your customers wish to see your business online and have instant access to your products or services.
Online Grocery Store is an e-commerce website, which retails various grocery products. This project allows viewing various products available enables registered users to purchase desired products instantly using Paytm, UPI payment processor (Instant Pay) and also can place order by using Cash on Delivery (Pay Later) option. This project provides an easy access to Administrators and Managers to view orders placed using Pay Later and Instant Pay options.
In order to develop an e-commerce website, a number of Technologies must be studied and understood. These include multi-tiered architecture, server and client-side scripting techniques, implementation technologies, programming language (such as PHP, HTML, CSS, JavaScript) and MySQL relational databases. This is a project with the objective to develop a basic website where a consumer is provided with a shopping cart website and also to know about the technologies used to develop such a website.
This document will discuss each of the underlying technologies to create and implement an e- commerce website.
2. Threads
Threads are lightweight processes as the overhead
of switching between threads is less
The can be easily spawned
The Java Virtual Machine spawns a thread when
your program is run called the Main Thread
3. Why do we need
threads?
To enhance parallel processing
To increase response to the user
To utilize the idle time of the CPU
Prioritize your work depending on priority
4. Example
• Consider a simple web server
• The web server listens for request and serves it
• If the web server was not multithreaded, the requests
processing would be in a queue, thus increasing the
response time and also might hang the server if there
was a bad request.
• By implementing in a multithreaded environment, the
web server can serve multiple request simultaneously
thus improving response time
5. Creating
threads
In java threads can be created by
extending the Thread class or
implementing the Runnable Interface
It is more preferred to implement the
Runnable Interface so that we can extend
properties from other classes
Implement the run() method which is the
starting point for thread execution
6. Running threads
• Example
class mythread implements Runnable{
public void run(){
System.out.println(“Thread Started”);
}
}
class mainclass {
public static void main(String args[]){
Thread t = new Thread(new mythread()); // This is the way to
instantiate a thread implementing runnable
interface
t.start(); // starts the thread by running the run method
}
}
• Calling t.run() does not start a thread, it is just a
simple method call.
• Creating an object does not create a thread, calling
start() method creates the thread.
7. Synchronization
Synchronization is prevent
data corruption
Synchronization allows
only one thread to perform
an operation on a object at
a time.
If multiple threads require
an access to an object,
synchronization helps in
maintaining consistency.
8. Example
public class Counter{
private int count = 0;
public int getCount(){
return count;
}
public setCount(int count){
this.count = count;
}
}
In this example, the counter tells how many an access
has been made.
If a thread is accessing setCount and updating count
and another thread is accessing getCount at the same
time, there will be inconsistency in the value of count.
9. Fixing the example
public class Counter{
private static int count = 0;
public synchronized int getCount(){
return count;
}
public synchoronized setCount(int count){
this.count = count;
}
}
By adding the synchronized keyword we make sure that
when one thread is in the setCount method the other
threads are all in waiting state.
The synchronized keyword places a lock on the object,
and hence locks all the other methods which have the
keyword synchronized. The lock does not lock the
methods without the keyword synchronized and hence
they are open to access by other threads.
10. What about static
methods?
public class Counter{
private int count = 0;
public static synchronized int getCount(){
return count;
}
public static synchronized setCount(int count){
this.count = count;
}
}
In this example the methods are static and hence are
associated with the class object and not the instance.
Hence the lock is placed on the class object that is,
Counter.class object and not on the object itself. Any other non
static synchronized methods are still available for access by
other threads.
11. Common
Synchronization mistake
public class Counter{
private int count = 0;
public static synchronized int getCount(){
return count;
}
public synchronized setCount(int count){
this.count = count;
}
}
The common mistake here is one method is static
synchronized and another method is non static synchronized.
This makes a difference as locks are placed on two different
objects. The class object and the instance and hence two
different threads can access the methods simultaneously.
12. Object locking
• The object can be explicitly locked in this way
synchronized(myInstance){
try{
wait();
}catch(InterruptedException ex){
}
System.out.println(“Iam in this “);
notifyAll();
}
• The synchronized keyword locks the object. The wait keyword waits for
the lock to be acquired, if the object was already locked by another
thread. Notifyall() notifies other threads that the lock is about to be
released by the current thread.
• Another method notify() is available for use, which wakes up only the next
thread which is in queue for the object, notifyall() wakes up all the threads
and transfers the lock to another thread having the highest priority.
13. 13
Thread Synchronization
• Monitors
• Object with synchronized methods
• Any object can be a monitor
• Methods declared synchronized
• public synchronized int myMethod( int x
)
• Only one thread can execute a synchronized
method at a time
• Obtaining the lock and locking an object
• If multiple synchronized methods, only one may be
active
• Java also has synchronized blocks of code
14. 14
Thread Synchronization
• Thread may decide it cannot proceed
• May voluntarily call wait while accessing a
synchronized method
• Removes thread from contention for monitor object and
processor
• Thread in waiting state
• Other threads try to enter monitor object
• Suppose condition first thread needs has now been met
• Can call notify to tell a single waiting thread to enter
ready state
• notifyAll - tells all waiting threads to enter ready
state
15. 15
Daemon Threads
• Daemon threads
• Threads that run for benefit of other
threads
• E.g., garbage collector
• Run in background
• Use processor time that would
otherwise go to waste
• Unlike normal threads, do not
prevent a program from terminating -
when only daemon threads remain,
program exits
• Must designate a thread as daemon
before start called:
void setDaemon( true );
• Method boolean isDaemon()
• Returns true if thread is a daemon
thread
16. SchedulingThreads
I/O operation completes
start()
Currently executed
thread
Ready queue
•Waiting for I/O operation to be completed
•Waiting to be notified
•Sleeping
•Waiting to enter a synchronized section
Newly created
threads
What happens when
a program with a
ServerSocket calls
accept()?
20. Deadlock Example
public class BankAccount {
private float balance;
public synchronized void deposit(float amount) {
balance += amount;
}
public synchronized void withdraw(float amount) {
balance -= amount;
}
public synchronized void transfer(float amount,
BankAccount target) {
withdraw(amount);
target.deposit(amount);
}
}
21. public class MoneyTransfer implements Runnable {
private BankAccount from, to;
private float amount;
public MoneyTransfer(
BankAccount from, BankAccount to, float amount) {
this.from = from;
this.to = to;
this.amount = amount;
}
public void run() {
source.transfer(amount, target);
}
}
22. BankAccount aliceAccount = new BankAccount();
BankAccount bobAccount = new BankAccount();
...
// At one place
Runnable transaction1 =
new MoneyTransfer(aliceAccount, bobAccount, 1200);
Thread t1 = new Thread(transaction1);
t1.start();
// At another place
Runnable transaction2 =
new MoneyTransfer(bobAccount, aliceAccount, 700);
Thread t2 = new Thread(transaction2);
t2.start();
24. Thread Synchronization
We need to synchronized between
transactions, for example, the consumer-
producer scenario
25. Wait and Notify
Allows two threads to cooperate
Based on a single shared lock object
Marge put a cookie wait and notify Homer
Homer eat a cookie wait and notify Marge
Marge put a cookie wait and notify Homer
Homer eat a cookie wait and notify Marge
26. The wait() Method
The wait() method is part of the
java.lang.Object interface
It requires a lock on the object’s monitor to execute
It must be called from a synchronized method, or from a
synchronized segment of code. Why?