Lecture 23 25
Lecture 23 25
Lec 23-25
HANDOUTS
WEB DESIGN AND DEVELOPMENT
- 277 -
Lec – 23
Web Design & Development CS-506
Lecture 23
Multithreading
Introduction
Multithreading is the ability to do multiple things at once with in the same application. It
provides finer granularity of concurrency. A thread — sometimes called an execution
context or a lightweight process — is a single sequential flow of control within a
program.
Threads are light weight as compared to processes because they take fewer resources then
a process. A thread is easy to create and destroy. Threads share the same address space
i.e. multiple threads can share the memory variables directly, and therefore may require
more complex synchronization logic to avoid deadlocks and starvation.
// File ThreeLoopTest.java
//first loop
for (int i=1; i<= 5; i++)
System.out.println(“first ” +i);
// second loop
for (int j=1; j<= 5; j++)
System.out.println(“second ” + j);
// third loop
for (int k=1; k<= 5; k++)
System.out.println(“third ” + k);
} // end main
} // end class
- 278 -
Lec – 23
Web Design & Development CS-506
When the program executes, the loops are executed sequentially, one after the other. It
generates the following output.
- 279 -
Lec – 23
Web Design & Development CS-506
However, if we use multithreading — with one thread per loop — the program may
generate the following output.
Note: Each loop has 10 iterations in the ThreadTest program. Your output can be
different from the one given above.
--------------
Notice the difference between the outputs of the two programs. In ThreeLoopTest each
loop generated a sequential output while in ThreadTest the output of the loops got
intermingled i.e. concurrency took place and loops executed simultaneously
Let us code our first multithreaded program and try to learn how Java supports
multithreading.
- 280 -
Lec – 23
Web Design & Development CS-506
Java Threads
Java includes built-in support for threading. While other languages have threads bolted-
on to an existing structure. i.e. threads were not the part of the original language but latter
came into existence as the need arose.
All well known operating systems these days support multithreading. JVM transparently
maps Java Threads to their counter-parts in the operating system i.e. OS Threads. JVM
allows threads in Java to take advantage of hardware and operating system level
advancements. It keeps track of threads and schedules them to get CPU time. Scheduling
may be pre-emptive or cooperative. So it is the job of JVM to manage different tasks of
thread. Let’s see how we can create threads?
• Using Interface
• Using Inheritance
- 281 -
Lec – 23
Web Design & Development CS-506
- 282 -
Lec – 23
Web Design & Development CS-506
Now we will re-write the ThreeLoopTest program by using Java Threads. At first we will
use the Interface approach and then we will use Inheritance.
// File Worker.java
public class Worker implements Runnable {
private String job ;
//Constructor of Worker class
public Worker (String j ){
job = j;
}
//Implement run() method of Runnable interface
public void run ( ) {
for(int i=1; i<= 10; i++)
System.out.println(job + " = " + i);
}
} // end class
// File ThreadTest.java
public class ThreadTest{
public static void main (String args[ ]){
//instantiate three objects
Worker first = new Worker (“first job”);
Worker second = new Worker (“second job”);
Worker third = new Worker (“third job”);
- 283 -
Lec – 23
Web Design & Development CS-506
Following code is similar to the code given above, but uses Inheritance instead of
interface
// File Worker.java
} // end class
// File ThreadTest.java
}//end main
} // end class
--------------
- 284 -
Lec – 23
Web Design & Development CS-506
Thread Priorities
Threads provide a way to write concurrent programs. But on a single CPU, all the threads
do not run simultaneously. JVM assigns threads to the CPU based on thread priorities.
Threads with higher priority are executed in preference to threads with lower priority. A
thread’s default priority is same as that of the creating thread i.e. parent thread.
A Thread’s priority can be any integer between 1 and 10. We can also use the following
predefined constants to assign priorities.
setPriority(int priority)
It changes the priority of this thread to integer value that is passed. It throws an
IllegalArgumentException if the priority is not in the range MIN_PRIORITY to
MAX_PRIORITY i.e. (1–10).
For example, we can write the following code to change a thread’s priority.
At any given time, when multiple threads are ready to be executed, the runtime system
chooses for execution the Runnable thread that has the highest priority. Only when that
thread stops, yields (will be explained later), or becomes Not Runnable will a lower-
priority thread start executing. If two threads of the same priority are waiting for the
CPU, the scheduler arbitrarily chooses one of them to run. The chosen thread runs until
one of the following conditions becomes true:
- 285 -
Lec – 23
Web Design & Development CS-506
Then the second thread is given a chance to run, and so on, until the interpreter exits.
Consider the following figure in which threads of various priorities are represented by
capital alphabets A, B, …, K. A and B have same priority (highest in this case). J and K
have same priority (lowest in this case). JVM start executing with A and B, and divides
CPU time between these two threads arbitrarily. When both A and B comes to an end, it
chooses the next thread C to execute.
- 286 -
Lec – 23
Web Design & Development CS-506
// File PriorityEx.java
public class PriorityEx{
public static void main (String args[ ]){
//instantiate two objects
Worker first = new Worker (“first job”);
Worker second = new Worker (“second job”);
}//end main
} // end class
Output
- 287 -
Lec – 23
Web Design & Development CS-506
First a Java thread priority may map differently to the thread priorities of the underlying
OS. It is because of difference in priority levels of JVM and underlying OS. For example
Second, starvation can occur for lower-priority threads if the higher-priority threads never
terminate, sleep, or wait for I/O indefinitely.
- 288 -
Lec – 23
Web Design & Development CS-506
References:
- 289 -
Lec – 24
Web Design & Development CS-506
Lecture 24
More on Multithreading
In this handout, we’ll cover different aspects of multithreading. Some examples are given
to make you understand the topic of multithreading. First we will start with an example
that reads data from two text files simultaneously.
first 1
first 2
first 3
first 4
first 5
first 6
first 7
first 8
first 9
first 10
first.txt
second 1
second 2
second 3
second 4
second 5
second 6
second 7
second 8
second 9
second 10
second.txt
- 290 -
Lec – 24
Web Design & Development CS-506
// File ReadFile.java
import java.io.*;
public class ReadFile implements Runnable{
//attribute used for name of file
String fileName;
// param constructor
public ReadFile(String fn){
fileName = fn;
}
while(line != null) {
System.out.println(line);
line = br.readLine();
}
fr.close();
br.close();
- 291 -
Lec – 24
Web Design & Development CS-506
Next, look at the Test.java class that contains the main() method.
// File Test.java
public class Test {
public static void main (String args[]){
}
}
Output
On executing Test class, following kind output would be generated:
- 292 -
Lec – 24
Web Design & Development CS-506
- 293 -
Lec – 24
Web Design & Development CS-506
Below is the code of SleepEx.java that contains the main() method. It will use
the Worker class created above.
// File SleepEx.java
public class SleepEx {
public static void main (String args[ ]){
// starting thread
t1.start();
t2.start();
}
} // end class
Output
On executing SleepEx.java, the output will be produced with exact alternations
between first thread & second thread. On starting threads, first thread will go to sleep
for 100 ms. It gives a chance to second thread to execute. Later this thread will also
go to sleep for 100 ms. In the mean time the first thread will come out of sleep and
got a chance on processor. It will print job on console and again enters into sleep state
and this cycle goes on until both threads finished the run() method
- 294 -
Lec – 24
Web Design & Development CS-506
// File DelayEx.java
public class DelayEx {
public static void main (String args[ ]){
System.out.println(“main thread going to sleep”);
try {
// the main thread will go to sleep causing delay
Thread.sleep(100);
}catch (Exception ex){
System.out.println(ex);
}
System.out.println(“main thread coming out of sleep”);
} // end main()
} // end class
Output
On executing DelayEx class, you will experience a delay after the first statement
displayed. The second statement will print when the time interval expired. This has been
show below in the following two diagrams:
- 295 -
Lec – 24
Web Design & Development CS-506
yield( ) method
- Allows any other threads of the same priority to execute (moves itself to the end
of the priority queue)
- If all waiting threads have a lower priority, then the yielding thread resumes
execution on the CPU
- Generally used in cooperative scheduling schemes
// File Worker.java
public class Worker implements Runnable {
private String job ;
//Constructor of Worker class
public Worker (String j ){
job = j;
}
//Implement run() method of Runnable interface
public void run ( ) {
for(int i=1; i<= 10; i++) {
} // end for
} // end run
} // end class
- 296 -
Lec – 24
Web Design & Development CS-506
Below is the code of YieldEx.java that contains the main() method. It will
use the Worker class created above.
// File YieldEx.java
public class YieldEx {
public static void main (String args[ ]){
// starting thread
t1.start();
t2.start();
}
} // end class
Output
Since both threads have the same priority (until we change the priority of some thread
explicitly). Therefore both threads will execute on alternate basis. This can be
confirmed from the output given below:
- 297 -
Lec – 24
Web Design & Development CS-506
start()
new
ready
I/O completed
notify()
times expires
or interrupted blocked
dispatch
waiting yield()
sleeping
sleep()
wait()
dead
run completes
New state
- When a thread is just created
Ready state
- Thread’s start() method invoked
- Thread can now execute
- Put it into the Ready Queue of the scheduler
Running state
- Thread is assigned a processor and now is running
Dead state
- Thread has completed or exited
- Eventually disposed off by system
- 298 -
Lec – 24
Web Design & Development CS-506
Thread’s Joining
- Used when a thread wants to wait for another thread to complete its run( ) method
- For example, if thread2 sent the thread2.join() message, it causes the currently
executing thread to block efficiently until thread2 finishes its run() method
- Calling join method can throw InterruptedException, so you must use try-
catch block to handle it
// File Worker.java
public class Worker implements Runnable {
private String job ;
public Worker (String j ){
job = j;
}
public void run ( ) {
for(int i=1; i<= 10; i++) {
System.out.println(job + " = " + i);
} // end for
} // end run
} // end class
The class JoinEx will demonstrate how current running (main) blocks until the
remaining threads finished their run( )
// File JoinEx.java
public class JoinEx {
public static void main (String args[ ]){
Worker first = new Worker ("first job");
Worker second = new Worker ("second job");
Thread t1 = new Thread (first );
Thread t2 = new Thread (second);
System.out.println("Starting...");
// starting threads
t1.start();
t2.start();
// The current running thread (main) blocks until both
- 299 -
Lec – 24
Web Design & Development CS-506
Output
=================================
- 300 -
Lec – 24
Web Design & Development CS-506
References:
- 301 -
Lec – 25
Web Design & Development CS-506
Lecture 25
Introduction
Because of the wide spread use of internet, web based applications are becoming vital
part of IT infrastructure of large organizations. For example web based employee
performance management systems are used by organizations for weekly or monthly
reviews of employees. On the other hand online course registration and examination
systems can allow students to study while staying at their homes.
Web Applications
In general a web application is a piece of code running at the server which facilitates a
remote user connected to web server through HTTP protocol. HTTP protocol follows
stateless Request-Response communication model. Client (usually a web-browser) sends
a request to Server, which sends back appropriate response or error message.
A web server is a software which provides users, access to the services that are present on
the internet. These servers can provide support for many protocols used over internet or
intranet like HTTP, FTP, telnet etc
HTTP Basics
A protocol defines the method and way of communication between two parties. For
example when we talk to our teacher we use a certain way which is different from the
way that we adopt with our fiends or parents. Similarly there are many different protocols
used by computers to communicate with each other depending on applications.
- 302 -
Lec – 25
Web Design & Development CS-506
For example an Echo Server only listens to incoming name messages and sends back
hello message, while HTTP protocol uses various types of request-response messages.
- Header Fields: Optional headers can be used by client to tell server extra
information about request e.g. client software and content type that it understands.
- 303 -
Lec – 25
Web Design & Development CS-506
- Other request headers like FROM (email of the person responsible for request)
and VIA (used by gateways and proxies to show intermediate sites the request
passes) can also be used.
Request Parameters
- Header Fields: Servers use these fields to tell client about server information like
configurations and software etc.
- Body: Data sent by server as part of response that is finally seen by the user.
- 304 -
Lec – 25
Web Design & Development CS-506
o 100-199
Codes in the 100s are informational, indicating that the client
should respond with some other action.
o 200-299
Values in the 200s signify that the request was successful.
o 300-399
Values in the 300s are used for files that have moved and usually
include a Location header indicating the new address.
o 400-499
Values in the 400s indicate an error by the client.
o 500-599
Codes in the 500s signify an error by the server.
- 305 -
Lec – 25
Web Design & Development CS-506
- 306 -
Lec – 25
Web Design & Development CS-506
- 307 -
Lec – 25
Web Design & Development CS-506
While in case of dynamic web pages server executes an application which generates
HTML web pages according to specific requests coming from client. These dynamically
generated web pages are sent back to client with the response.
We need to create dynamic web pages when the content of site changes frequently and
client specific response is required. Some of the scenarios are listed below
- The web page is based on data submitted by the user. e.g. results page from search
engines and order confirmation pages at on line stores.
- 308 -
Lec – 25
Web Design & Development CS-506
- The Web page is derived from data that changes frequently. e.g. a weather report
or news headlines page.
- The Web page uses information from databases or other server-side resources.
e.g. an e-commerce site could use a servlet to build a Web page that lists the
current price and availability of each item that is for sale.
- 309 -
Lec – 25
Web Design & Development CS-506
- Using technologies for developing web pages that include dynamic content.
- Developing web based applications which can produce web pages that contain
information that is connection-dependent or time-dependent.
Dynamic web content development technologies have evolved through time in speed,
security, ease of use and complexity. Initially C based CGI programs were on the server
Then template based technologies like ASP and PHP were then introduced which allowed
ease of use for designing complex web pages. Sun Java introduced Servlets and JSP that
provided more speed and security as well as better tools for web page creation.
- 310 -
Lec – 25
Web Design & Development CS-506
- Presentation Layer:
Provides a user interface for client to interact with application. This is the only
part of application visible to client.
- Business Layer
The business or service layer implements the actual business logic or functionality
of the application. For example in case of online shopping systems this layer
handles transaction management.
- Data Layer
This layer consists of objects that represent real-world business objects such as an
Order, OrderLineItem, Product, and so on.
- 311 -
Lec – 25
Web Design & Development CS-506
- 312 -
Lec – 25
Web Design & Development CS-506
References:
- 313 -