Title: Internet and Java Revolutions Impact on Education
1Internet and Java Revolutions Impact on Education
Rajkumar School of Computing Queensland
University of Technology Brisbane,
Australia Email rajkumar_at_fit.qut.edu.au URL
http//www.fit.qut.edu.au/rajkumar
2Motivation
- Potential delivery sites are widely distributed
- Information is rapidly changing
- Connections to the Internet have become
ubiquitous - Different learners have different needs
3Agenda
- Internet and its Evolution
- Internet Tools
- Web and its Programming
- Internet as a delivery Vehicle
- Java for Internet Programming
- Java Nuts and Bolts
- Java Platform
- Developing Applets and Applications
- Challenges and Future Directions
4What is the Internet ?
- It is a global network of computers
- that communicate with each other
- using a variety of protocols and
- overcoming various communication
- barriers.
- It is like International Telephone
- System
5Internet Technology Evolution
- Internet is much bigger than what we think
- More than 25 years old
- More than doubling every year
- Technology effect
- suddenly every body sees the need for a
technology - like the radio or the TV
- 10 terabytes flows everyday
6Installed base and Growth rate for telephone
lines, mobile phones, and Internet hots
Installed, 1995 1994-95 Growth
Rates () Income Group/ Phone
Mobile Internet Phone Mobile
Internet Region Lines Phones
Hosts Lines Phones Hosts Lower
Income 2.0 0.12 1.35 35.7 135.1 246.0 Lower-
Middle 9.1 0.33 73.31 8.7 105.1 167.0 Upper -
Middle 14.5 1.34 380.13 6.4 66.8 111.9 High 53.
2 8.70 10749.23 3.6 55.6 97.0 Africa 1.7 0.09 69
.14 7.9 60.5 81.4 Americas 29.0 5.17 8359.58 5.
4 42.3 91.5 Asia 5.4 0.62 121.70 14.7 108.3 150.
0 Europe 33.0 3.04 2732.24 3.6 59.5 112.2 Oceans
39.7 9.55 12845.55 4.0 85.7 88.8 World 12.1 1.
56 1661.89 7.0 60.4 97.8
Source ACM, Nov, 97 (phones, international
telecommunication union, hosts, network Wizards
7Internet
- Use of internet advertisement/elections/newspapers
- information is public
- Ubiquitous technology
- Network is the computer
- Intranets - internal TCP/IP nets
- PC accounts for 55 of total IT
- Applications tied to platform - API lock-in
8Internet Evolution
Internet everywhere Internet appliances Price
based services Live communities ? ? ? ? ? ? ?
On line connects to internet Secure
payments Multi media Authoring Java VRML HTML
File mail TCP/IP Webpages Netscape
10 of Market
20 of Market
Total Market
9 Early Internet
- Early Internet supported only email .
- File Transfer Protocol development - ftp sites.
- Network News was added to the Internet.
- Archie - A program to canvass anonymous ftp sites
and create a database of what is available - Gopher- A menu-driven interface used to search
for information. - Archie and Gopher could answer questions only
like what FTP server contains info about xxxx
10 World Wide Web
- World Wide Web conceptualized by Tim Berners-Lee
at CERN in Switzerland - Concept of Hypertext led to the development of
the Hypertext Markup Language (HTML) - Tim Berners-Lee proposed the Browser program
- Scientists at CERN designed a TCP/IP based
protocol to share Hypertext information called
HTTP. - WWW officially is described as a Wide-area
hypermedia information retrieval initiative
aiming to give universal access to a large
universe of documents.
11Viewing WWW pages
- View text, graphics, pictures, sounds, video
- Web Browser
- HyperText Markup Language (HTML)
- Computer Independent
- Operating System Independent
12Web Browsers
- Netscape Navigator
- Microsoft Internet Explorer
- Omni Web
- NCSA Mosaic
- Lynx (text only)
13Internet Organization
- Truly world-wide
- Multiple communication media types
14Internet Organization
Domains .edu .org .com .mil .biz Computers fi
fe.engr.vt.edu www.engr.vt.edu
15WWW Organization
Client
Client
Server
Server
Server
Client
Server
Client
Client
16Generating Web Pages
- Simple Text Editor
- Word Processor or other tool export
- e.g., Internet Assistant for Microsoft Word
- HTML Editor
- Open file in Netscape Composer
- Last step is to put the file(s) on an HTML server
17HTML
- Hypertext -A little Hype and a Little Text.
- Hypertext point to information which can be local
or remotely located. - HTML -Derivative of the SGML( Standard
Generalized Markup Language). - HTML -information , commands for the Browser for
formatting documents. - HTML -The de-facto language for publishing on the
Internet. - Hypermedia- Hyper-links to Multimedia.
18Internet Tools
- Browsers- A tool used to view documents on the
WWW - Web servers - Machines which run the HTTP-server
Software that respond to HTTP requests which it
receives - Authoring Tools - Editors specially made for
editing HTML documents - Filters -Tools to convert legacy documents to
HTML format - Scripting -Languages used for scripting
- WAIS- Wide Area Information Servers (WAIS) for
indexing and doing full text searches
19How does the Web work ?
- Web -Designed around Client/Server Architecture
- Web Clients ( Web Browsers ) -send requests for
documents to any Web Server - Web Server -Program that responds to HTTP
requests - Hyperlink
- Web client connects to the specified Web Server
- The server responds by sending the information
asked for - The Browser formats the received HTML data and
displays it
20How does the Web Work
Send the INFORMATION ABOUT C-DAC ACTS
HTTP
The client sends an HTTP message to a
computer running a Web Server program and asks
for a document
The information about C-DAC ACTS
The web server sends the hypermedia HTML
documents to the client. You end up seeing the
document on your screen
21HTML document
- ltHTMLgt
- ltTITLEgtCentre for Development of Advanced
Computing - lt/TITLEgt
- ltBODY BGCOLORE7CCCC TEXT000000
LINK0000FFgt - ...
- ...
- ltA HREFmailtowebmaster_at_cdacb.ernet.ingt
webmasterlt/Agt - lt/BODYgt
- lt/HTMLgt
22(No Transcript)
23URLs
- URLs- The Hypertext links we use today are known
as Universal Resource Locator - URLs-Each name is unique across the Internet
- An URL looks like this
- http//system.domain.ext999/dir1/dir2/dir3/file.h
tml?blue - Parts of a URL are,
- Service type, System Name, Port, Directory path,
Filename,Search Components or Variables - Service type, System Name, Directory path are the
required parts of the URL
24 CGI (Common Gateway Interface)
- CGI makes the Web a Two-way interface
- CGI -lets the user run a script when a web page
is accessed - Information from the Web Client is received
through simple fill-in-the-forms kind of
interface - FORMS - Integrates data sheets, menus , check
boxes - CGI makes the Web interactive
- CGI -complicated to setup ,requires PERL
knowledge - HTML books talk less about CGI
25Authoring tools and Filters
- Authoring tools- Editors for HTML documents
- Editors similar to WYSIWYG word processing
programs - Semi-WYSIWYG or completely WYSIWYG
- Provide syntax checking and correction
- Filters -Convert legacy documents to HTML format
- Filters are useful when the documents already
exist - Authoring tools- HoTMetaL, HTML Assistant
-Shareware
26Preconfigured v/s Integrated Internet Products
- Integrated Internet Products- From multiple
vendors - Preconfigured Systems- Web Server and a Client
ready to use - Suns Netra Internet Server
- SGIs WebFORCE Indy and WebFORCE Challenge S
- Apples Internet Server Solution
- DECs Internet AlphaServer
- Integraphs Web Server 10
27Future Directions
- Additions to HTML (Grammar, Maths, Display
control) - VRML (Virtual Reality Markup Language)
- Security - Using Scrambling and Encryption
- Common Client Interface (CCI)- Allows Clients to
pass information back and forth between the
Browser and the External Viewer - Charge Mechanisms
- Performance Enhancements- Sending a page and
graphics for that page in one connection
28Internet in Education
Creating Your Own Page HTML Tags (Title,
Body, images, etc.) Basic HTML code file
structure Links and Anchors Linking it
elsewhere Moving around the WWW Making
it all Look Pretty Use components such as
- WWW Forms, Frames, Sound, Video, -
Animation, WWW Plugins Make web attractive
through Adding web applications -
customer enquiry - Free applications
Institution Web Site - about the
university - faculties and department
details - research facilities, area, and
groups - faculty members details with their
publications Admission Process - course
announcement, - making available details of
course - admission applications, -
announcement of selection University
Facilities - computing facilities,
accommodation, recreation, etc.. Teaching
Process - Use of WWW in the Curriculum -
Homework and Quizzes - Virtual Classroom -
Virtual Lectures - Student Interaction - Q
A
29Internet as a delivery Vehicle
30Interesting URLs
- http//www.whitehouse.gov ( The WhiteHouse)
- http//www.w3.org (Everything about the WWW)
- http//sunsite.unc.edu (Software on Sun)
- http//www.indnet.org (India Net Foundation
Services) - telnet//www.arbornet.org (Free Public Access
Unix System) - http//www.infoseek.com (Search engines, Add URL)
- http//www.infophil.com (World Alumni on the net)
- http//www.rocketmail.com (Free Email )
- http//members.tripod.com (Free Website,2MB
space) - http//www.bangaloreonline.com (Offers virtual
web servvices for compinies to host their
website). - http//www.prajavani.com (Kannada news paper on
web)
31Class Sites To Visit
- http//truth.phil.vt.edu/wwwcourses.html
- http//http//fiddle.visc.ece.vt.edu/courses/ee250
4/ - http//adept.stanford.edu/
- http//www.aoe.vt.edu/aoe5104.html
- http//nersp.nerdc.ufl.edu/cgs2422/
- http//www.sloan.org/oakley/misc/IMNews.html
- http//www.eng.fsu.edu/net98.html
32API Bottleneck
MAC
PC
LAN
LAN
Server
Network
SUN
33The OS - Platform lock
Applications tied to OS OS tied to Platform
Application
Application
OS
Application
34The Web
Seeded by HTML from CERN Revolutionised by
MOSAIC Standardised, universal interface to
data Graphical
Application
Application
BROWSER
OS
OS
OS
OS
Application
Application
Broadcast capability - publish once, reach
millions
35Making life easier!
- Data on the web
- Browser platform independent
- Click on application - run on any machine
- Java the programming language of the 21 century
36Java and Java Computing
37Java - An Introduction
- Java - The new programming language from Sun
Microsystems - Java -Allows anyone to publish a web page with
Java code in it - Java - CPU Independent language
- Created for consumer electronics
- Java - James , Arthur Van , and others
- Java -The name that survived a patent search
- Oak -The predecessor of Java
- Java is C --
38Java From 10,000 Ft.
- According to the world, Java is...
- According to Sun, Java is...
- On closer inspection, Java is
39According to the World, Java Is...
- Snazzy Web pages
- The cross-platform language we want
- The rest-of-the-worlds answer to Bill
- The C replacement we need
- The C replacement we dont need
- A bunch of hype
40According to Sun, Java is...
- Simple and Powerful
- Object Oriented
- Portable
- Architecture Neutral
- Distributed
- Multi-threaded
- Robust, Secure/Safe
- Interpreted
- High Performance
- Dynamic pogramming language/platform.
Buzzword compliant!
41On Closer Inspection, Java is...
- Simple
- Pure
- Portable
- Surprisingly effective
42As a whole, Java is a Comprehensive Programming
Solution
- Object Oriented
- Portable
- High Performance
- Geared for Distributed Environments
- Secure
43Java as Object Oriented
- Objects all the way down
- Simple and Familiar C Lite
- No Pointers!
- Garbage Collector
- Dynamic Binding
- Single Inheritance with Interfaces
44Java as Portable
- Unlike other language compilers, Java complier
generates code (byte codes) for Universal
Machine. - Java Virtual Machine (JVM) Interprets bytecodes
at runtime - Architecture Neutral
- No Link Phase
- Higher Level Portable Features AWT, Unicode
45Total Platform Independence
JAVA COMPILER
(translator)
JAVA BYTE CODE
(same for all platforms)
JAVA INTERPRETER
(one for each different system)
Windows 95
Macintosh
Solaris
Windows NT
46Java Write Once, Run Anywhere
47 Architecture Neutral Portable
- Java Compiler -Java source code to bytecode
- Bytecode - an intermediate form, closer to
machine representation - A virtual machine on any target platform
interprets the bytecode - Porting the java system to any new platform
involves writing an interpreter that supports the
Java Virtual Machine - The interpreter will figure out what the
equivalent machine dependent code to run
48Java as High Performance
- JVM uses lean and mean bytecodes
- Small binary class filtes
- Just-in-time Compilers
- Multithreading
- Native Methods
49Java in the World of Distributed Computing
- Class Loader
- Lightweight Binary Class Files
- Multithreading
- Dynamic
- Good communication constructs
- Secure
50Java as Secure
- Language designed as safe
- Strict compiler
- Dynamic Runtime Loading (Verifier)
- Runtime Security Manager
51Object Oriented Languages -a Comparison
52Java better than C ?
- No Typedefs, Defines, or Preprocessor
- No Global Variables
- No Goto statements
- No Pointers
- No Unsafe Structures
- No Multiple Inheritance
- No Operator Overloading
- No Automatic Coercions
- No Fragile Data Types
?
53Basic Data Types
- Types
- boolean either true of false
- char 16 bit Unicode 1.1
- byte 8-bit integer (signed)
- short 16-bit integer (signed)
- int 32-bit integer (signed)
- long 64-bit integer (singed)
- float 32-bit floating point (IEEE 754-1985)
- double 64-bit floating point (IEEE 754-1985)
- String (class for manipulating strings)
- Java uses Unicode to represent characters
internally
54 - Java Integrates
- Power of Compiled Languages
- and
- Flexibility of Interpreted Languages
55Two Types of JavaApplications
- Different ways to write/run a Java codes are
- Application- A stand-alone program that can be
invoked from command line . A program that has a
main method - Applet- A program embedded in a web page , to be
run when the page is browsed . A program that
contains no main method - Application -Java interpreter
- Applets- Java enabled web browser (Linked to HTML
via ltAPPLETgt tag. in html file)
56 Java Environment/ Life Cycle of Java Code
Runtime Environment
Compile-time Environment
Class Loader Bytecode Verifier
Java Class Libraries
Java Source (.java)
Java Bytecodes move locally or through network
Java Virtual machine
Java Compiler
Runtime System
Java Bytecode (.class )
Operating System
Hardware
57Java Development Kit
- javac - The Java Compiler
- java - The Java Interpreter
- jdb- The Java Debugger
- appletviewer -Tool to run the applets
- javap - to print the Java bytecodes
- javaprof - Java profiler
- javadoc - documentation generator
- javah - creates C header files
58Hello Internet
- // hello.java Hello Internet program
- class HelloInternet
-
- public static void main(String args)
-
- System.out.println(Hello Internet)
-
59Program Processing
- Compilation
- javac hello.java
- results in HelloInternet.class
- Execution
- java HelloInternet
- Hello Internet
60Simple Java Applet
- // HelloWorld.java A sample applet
- import java.applet.Applet
- public class HelloWorld extends Applet
- public void paint(Graphics g)
-
- g.drawString(Hello World !,25,25)
-
-
61Calling an Applet
- ltHTMLgt
- ltTITLEgt Hello Worls Applet lt/TITLEgt
- ltAPPLET codeHelloWorld.class width500
height500gt - lt/APPLETgt
- lt/HTMLgt
62Execution of Applets
4
2
5
3
1
Accessing from CRAY Corp. (USA)
APPLET Development hello.java AT CDAC-India
The browser creates a new window and a new
thread and then runs the code
hello.class AT C-DACS WEB SERVER
Create Applet tag in HTML document
Hello Java
ltapp Hellogt
The Internet
Hello
63Web Perspective
- How did Web interactions work?
- How do they work with Java?
- Distributed Java objects and the Web
64Classical Web Perspective
65Java Web Perspective
66Significance of downloading Applets
- Interactive WWW
- Flashy animation instead of static web pages
- Applets react to users input and dynamically
change - Display of dynamic data
- WWW with Java - more than a document publishing
medium - http//www.javasoft.com/applets/alpha/applets/Stoc
kDemo/standalone.html
67Power of Java and the Web
- Deliver applications, not just information
- Eliminate porting
- Eliminate end-user installation
- Slash software distribution costs
- Reach millions of customers - instantly
68Lifecycle of Java Code
69Bytecode Verifier
- Called when class is first loaded in runtime
environment - Verifies bytecodes meet certain set of properties
- Verifier uses Theorem Prover
- Verified code runs faster
- After verification, interpreter defines memory
layout
70Class Loader
- Unique Namespace for each origin
- Local namespace classes are called built-ins
- Prevents class spoofing
71Security Manager
- Prevents unauthorized disk read/writes
- Restricts network access
- Other access restrictions (native methods)
- Implementation is browser dependent
72General Language Features
- C/C like syntax
- No pointers
- Objects all the way down
- Objects request services of other objects through
messages - Messages result in invocation of class methods
73Removed From C
- Operator overloading
- Pointers and Array/pointers
- Multiple-inheritance of implementation
- Enum, typedef, define
- Copy constructors, destructors
- Templates
- And other stuff....
74Added or Improved over C
- Interfaces type Vs. class
- Garbage collection
- Exceptions (More powerful than C)
- Strings
- Instanceof
- Package
- Multi-threads
75Declaring Classes
- class Queue
- Object data
- Queue (int size) // Constructor
- data new Objectsize
-
- void add(Object o)
- // add to array in class specific
manner... - // other methods
76Inheritance in Java
- class PriorityQueue extends Queue
- PriorityQueue (int size) // Constructor
- super(size) // Call Queue constructor use
data - // Class specific initialization
-
- void add(Object o) // Overriden method
- // add to array in class specific
manner... - // other methods
77Creating and Using Objects
- PriorityQueue p new PriorityQueue(10) // Q of
size 10 - String s This is a string
- p.add(s) // Add string to priority queue
- p.add(this) // Add object calling this code to
queue...
78Class Methods and Variables
- int pi Math.PI
- int theMax Math.max(x,6)
- Definitions
- public final static double PI
- 3.14159265358979323846
- public static int max(int a, int b)
79Access Rules
- public
- private
- protected
- package (Default - no keyword)
80Using Threads
- Define a Thread class
- public MyThread extends Thread
- public void run() // Override default
method - while (true) // do custom code
- .
- Using the thread
- MyThread t new MyThread()
- t.start() // Start the thread...
- Detailed discussion on Threads, later
81Strings
- The language defines strings as objects
- doSomething("abc" "cde")
- doSomething(String s) ..
- String abc new String(Hello)
- System.out.println(abc)
82Exceptions
- Try, catch, throw, finally
- try failure_Prone_Call()
- catch (File_Exception f) ....Handle f....
- finally do_This_Regardless()
- Exception signatures are checked void foo()
throws TypeC - Exceptions must be caught or declared
- Errors do not have to be caught
- Surprisingly effective at producing robust code
83Exception Handling
- try
- // some code here...
- int x y/z
-
- catch (ArithmeticException e)
- System.out.println(Divide by zero error!)
-
- catch (Exception e)
- System.out.println(Some other error!)
-
- finally // Optional...
- z
84More about Exceptions
- Very Strict Exception Handling Rules
- All methods that throw an exception must be
caught or rethrown (except for runtime
exceptions) - Hierarchy of Exception classes
- Can create custom Exception classes
- Cause own exception with throw clause
85Interfaces
- Interfaces are a way to declare an Abstract type
without implementation - Interfaces are like classes but without
implementation - Interfaces are expressions of pure designs only
- Example Interface
- interface sqrt
- int sqrt(int newint)
-
- Implementing an interface
- class myclass implements sqrt
- ..........
86Interface Type and Sub-Type
- Pure type of a set of objects
- interface Observer
- void update (Observable o)
-
- Interfaces can form a graph
- interface List_Observer extends Observer
-
- void updateItem (int position)
-
87Class Implements Interface
- Complete type/class separation possible
- class Order implements Observer
-
- public void update (Object o)
-
- // do stuff toupdate
-
- // data and other implementation
-
- Any object can support multiple interfaces
- Client can see its types separately or conjoined
- A powerful approach to design, roles,
distribution, design patterns - Takes a little bit of getting used to
88Implementation Inheritance
- Single inheritance of implementation
- class X extends W implements E, F
-
- // Stuff in class X
-
89Interfaces and Classes!
90Uses of Interfaces
- There are considerable problems due to Multiple
Inheritance - Interfaces in a way add multiple inheritance to
Java - Interfaces may be extended too, more than once
91Garbage Collected
- No more manual memory management
- class Recycler
-
- public void recycle ()
-
- Hashtable t
- for (int i0 ilt100 i)
-
- t new Hashtable()
-
-
-
- Significant elimination of programming bugs
92instanceof and casts
- Run-time type query
- void foo (Object x)
-
- if (x instanceof Order)
-
- Order o (Order) x
- // ...Do stuff with o
-
-
- Can query for an interface or a class
93Packages
- No more include
- package Shopper
- import java.awt.
- // define Shopper interfaces and classes
- Provides namespace and export features
- class, sub-class, intra-package, and inter
package control - Package typically maps to a directory
94Packages and Utilities
- Packages - helps in organizeing classes i.e.,
keep the class name space compartmentalized - For Naming and Visibility
- Similar to C Class Libraries
- Bring in classes from other packages with the
import keyowrd - Ad hoc collection of utility classes
- Storing collection of objects
- Interfacing with low-level system functions
- Math functions (java.lang.Math)
95Rich Object Environment
- Core Classes
- language
- Utilities
- Input/Output
- Low-Level Networking
- Abstract Graphical User Interface
- Internet Classes
- TCP/IP Networking
- WWW and HTML
- Distributed Programs
96Main Packages
- java.lang
- java.util
- java.io
- java.awt
- java.awt.image
- java.applet
- java.net
97java.lang Core Classes
- Base Class Object
- String
- String s This is number 6
- Math
- Math.sqrt(4.0)
- System
- System.out.println(An error occurred)
- System.exit(1)
98java.lang Type Wrappers
- Literals int, double, boolean, char
- Literals wrapped in Classes Integer, Double,
Boolean, Character - Literals used for high performance
- Examples
- int x Integer.parseInt(6)
- Integer I new Integer(999)
- double dbl I.doubleValue()//Returns 999.000
99java.io - Filtering input streams
- try // Open the file...
- DataInputStream dis new DataInputStream(
new BufferedInputStream( - new FileInputStream(myFile)) )
- // Read lines until EOF is reached...
- String s
- while((s dis.readLine()) ! null) //
Read CR delimited lines - System.out.println(s)
- dis.close()
-
- // Handle any exceptions caused by the
process... - catch (IOException e)
- System.out.println(e.getMessage())
-
100GUI Programming in Java(AWT and Event Handling)
101AWT - Abstract Windowing Toolkit
- Single Windowing Interface on Multiple Platforms
- Supports functions common to all window systems
- Uses Underlying Native Window system
- AWT provides
- GUI widgets
- Event Handling
- Containers for widgets
- Layout managers
- Graphic operations
102AWT - Abstract Window Toolkit
- Portable GUI - preserves native look feel
- Standard GUI Components (buttons)
- Containers - Panels, Frames, Dialogs
- Graphics class for custom drawing
- Layouts responsible for actual positioning of
components - BorderLayout, GridLayout, FlowLayout, null layoit
103Adding Components via Layouts
- setLayout(new BorderLayout())
- // Add text field to top
- add("North",new TextField())
- // Create the panel with buttons at the
bottom... - Panel p new Panel() // FlowLayout
- p.add(new Button("OK"))
- p.add(new Button("Cancel"))
- add("South",p)
104Adding Components via Layouts
105Popup Menu and Event Handling...
- //popup.java popup menu and event handling
- import java.applet.Applet
- import java.awt.
- import java.awt.event.
- public class popup extends Frame implements
ActionListener, MouseListener -
- TextField text1
- PopupMenu popup
- MenuItem menuitem1, menuitem2, menuitem3
- public popup()
-
- super( "Popup Menu" )
- setLayout(new FlowLayout())
- setBounds(10, 10, 300, 200 )
- setVisible(true)
- init()
-
- public void init()
-
106Popup Menu and Event Handling...
- menuitem1 new MenuItem("CPU")
- menuitem1.addActionListener(this)
- menuitem2 new MenuItem("Disk")
- menuitem2.addActionListener(this)
- menuitem3 new MenuItem("Memory")
- menuitem3.addActionListener(this)
- popup.add(menuitem1)
- popup.add(menuitem2)
- popup.add(menuitem3)
- add(popup)
- text1 new TextField(20)
- text1.setBounds(20, 40, 120, 30 )
- add(text1)
- addMouseListener(this)
-
- public void mousePressed(MouseEvent e )
-
- if( e.getModifiers() ! 0 )
- popup.show(this, e.getX(), e.getY() )
107Popup Menu and Event Handling
- public void mouseReleased( MouseEvent e )
- System.out.print("Mouse Released\n" )
- public void mouseEntered( MouseEvent e )
- System.out.print("Mouse Entered\n" )
- public void mouseExited( MouseEvent e )
- System.out.print("Mouse Exited\n" )
- public void actionPerformed( ActionEvent e )
-
- if( e.getSource() menuitem1 )
- text1.setText("CPU")
- if( e.getSource() menuitem2 )
- text1.setText("Disk")
- if( e.getSource() menuitem3 )
- text1.setText("Memory")
-
- public static void main( String args )
-
- popup p new popup()
-
108Custom Drawing
- // MyApplet.java draws rectangle with yellow
color fill - import java.applet.
- import java.awt.
- public class MyApplet extends Applet
-
- public synchronized void paint(Graphics g)
-
- int x,y,width,height
- Dimension dm size()
- x dm.width/4
- y dm.height / 4
- width dm.width / 2
- height dm.height / 2
- // Draw the rectangle in the center with
colors! - g.setColor(Color.blue)
- g.drawRect(x,y,width,height)
- g.setColor(Color.yellow)
- g.fillRect(x 1,y 1,width - 2,height -
2) -
109java.applet
- Applet
- Class representation of applet
- init() method called when first loaded
- start() when applets Web page becomes active
- stop() when user leaves Web Page
- Actually derived from AWT Panel
- AppletContext
- Hooks into Browser environment
- Can be used to link to another Web page
110A sample Applet
- // HelloApplet.java for processing applet
methods - import java.awt.
- import java.applet.
- public class HelloApplet extends Applet
-
- public void init()
-
- System.out.println("init() method
invoked") -
- public void start()
-
- System.out.println("start() method
invoked") -
- public void paint( Graphics g )
-
- System.out.println("paint() method
invoked") - g.drawString( "Hello World", 24, 25 )
-
- public void stop()
111Network/Socket Programming in Java
112java.net
- Used to manage
- URL streams
- Client/server sockets
- Datagrams
113Server side Socket Operations
- 1. Open Server Socket
- String server Socket slink
- DataOutputStream os
- DataInputStream is
- server new ServerSocket( PORT )
- 2. Wait for Client Request
- Socket client server.accept()
- 3. Create I/O streams for communicating to
clients - is new DataInputStream( client.getInputStream()
) - os new DataOutputStream( client.getOutputStre
am() ) - 4. Perform communication with client
- Receiive from client String line
is.readLine() - Send to client os.writeBytes("Hello\n")
- 5. Close sockets client.close()
- For multithreade server
- while(true)
- i. wait for client requests (step 2 above)
- ii. create a thread with client socket as
parameter (the thread creates streams (as in step
(3) and does communication as stated in (4).
Remove thread once service is provided.
114Client side Socket Operations
- 1. Get connection to server
- client new Socket( server, port_id )
- 2. Create I/O streams for communicating to
clients - is new DataInputStream( client.getInputStream()
) - os new DataOutputStream( client.getOutputStre
am() ) - 3. Perform communication with client
- Receiive from client String line
is.readLine() - Send to client os.writeBytes("Hello\n")
- 4. Close sockets client.close()
115Echo Server Client..
- //client.java client interface to server
- import java.io.
- import java.net.
- public class client
-
- int port_id
- String server Socket slink
- DataOutputStream os
- DataInputStream is
- DataInputStream kbd
- public client( String args )
-
- server args0
- port_id Integer.valueOf(args1).intValue(
) - try
-
- slink new Socket( server, port_id )
- os new DataOutputStream(
slink.getOutputStream() ) - is new DataInputStream(
slink.getInputStream() )
116Echo Server Client..
- catch( UnknownHostException e )
-
- System.err.println( "Don't know about
host " ) - System.exit(1)
-
- catch( IOException e )
-
- System.err.println( "Could not get I/O for the
connection to "server) - System.exit(1)
-
-
- void communicate()
-
- while(true)
-
- try
- System.out.print("Enter Input ltend to
stopgt ") - String line kbd.readLine()
- os.writeBytes( line"\n" )
117Echo Server Client..
- if( line.equals("end") )
- os.close() is.close() slink.close()
- break
-
- String line2 is.readLine()
- System.out.println("Output "line2)
-
- catch( IOException e )
- System.out.println(e)
-
-
- public static void main( String args )
-
- if( args.length lt 2 )
-
- System.out.println("Usage java client
server_name port_id" ) - System.exit(1)
-
- client cln new client( args )
118Echo Server ...
- // server.java echo server
- import java.io.
- import java.net.
- public class server
-
- // public final static int PORT 4779
- public static void main( String args )
-
- ServerSocket server null
- DataOutputStream os null
- DataInputStream is null
- boolean shutdown false
- if( args.length lt 1 )
-
- System.out.println( "Usage java server
port_num" ) - System.exit( 1 )
-
- int PORT Integer.valueOf(args0).intValue
() - try
119Echo Server ...
- catch( IOException e )
-
- System.err.println( "Could not get I/O for
the connection to ") -
- while(!shutdown)
-
- if( server ! null )
-
- try
-
- Socket client server.accept()
- System.out.println("Connected")
- InetAddress cip client.getInetAddres
s() - System.out.println( "Client IP Addr
"cip.toString()) - is new DataInputStream(
client.getInputStream() ) - os new DataOutputStream(
client.getOutputStream() ) - for()
-
- String line is.readLine()
120Echo Server ...
- if( line.startsWith("end" ) )
-
- shutdown true
- break
-
- os.writeBytes(line.toUpperCase())
- os.writeBytes("\n")
- System.out.println(line)
-
- is.close() client.close()
-
- catch( UnknownHostException e )
-
- System.err.println( "Server Open fails" )
-
- catch( IOException e )
-
- System.err.println( "Could not get I/O for the
connection to"args0) -
121Echo Server
- System.out.println( "Server Down" )
- try
- server.close()
- catch(IOException e)
-
-
122Multithreading in Java(A built-in feature in
Java)
123What are Threads?
- Thread is a piece of code that can execute in
concurrence with other threads. - It is a schedule entity on a processor
- Local state
- Global/ shared state
- PC
- Hard/Software Context
Thread Object
124Single and Multithreaded Processes
Single-threaded Process
Multiplethreaded Process
Threads of Execution
Multiple instruction stream
Single instruction stream
Common Address Space
125OSMulti-Processing, Multi-Threaded
Threaded Libraries, Multi-threaded I/O
Better Response Times in Multiple Application
Environments
Higher Throughput for Parallelizeable Applications
126Threaded Process Model
THREAD STACK
SHARED MEMORY
THREAD DATA
Threads within a process
THREAD TEXT
- Independent executables
- All threads are parts of a process hence
communication - easier and simpler.
127Levels of Parallelism Thread Granularity
Code-Granularity Code Item Large grain (task
level) Program Medium grain (control
level) Function (thread) Fine grain (data
level) Loop Very fine grain (multiple
issue) With hardware
Task i-l
Task i
Task i1
func1 ( ) .... ....
func2 ( ) .... ....
func3 ( ) .... ....
- Task
- Control
- Data
- Multiple Issue
a ( 0 ) .. b ( 0 ) ..
a ( 1 ).. b ( 1 )..
a ( 2 ).. b ( 2 )..
x
Load
128Multithreading - Uniprocessors
- Concurrency Vs Parallelism
P1
CPU
P2
P3
time
Number of Simulatneous execution units gt no of
CPUs
129Multithreading - Multiprocessors
Concurrency Vs Parallelism
CPU
P1
CPU
P2
CPU
P3
time
No of execution process no of CPUs
130Threads
- Java has built in thread support for
Multithreading - Synchronization
- Thread Scheduling
- Inter-Thread Communication
- currentThread start setPriority
- yield run getPriority
- sleep stop suspend
- resume
- Java Garbage Collector is a low-priority thread
131Threading Mechanisms...
- Create a class that extends the Thread class
- Create a class that implements the Runnable
interface
1321st method Extending Thread class
- 1st Method Extending the Thread class
- class MyThread extends Thread
-
- public void run()
-
- // thread body of execution
-
-
- Creating thread
- MyThread thr1 new MyThread()
- Start Execution
- thr1.start()
1332nd method Threads by implementing Runnable
interface
- class ClassName implements Runnable
-
- .....
- public void run()
-
- // thread body of execution
-
-
- Creating Object
- ClassName myObject new ClassName()
- Creating Thread Object
- Thread thr1 new Thread( myObject )
- Start Execution
- thr1.start()
134Multi-Threaded
- Thread and its subclasses run one thread per
instance - class MyThread extends Thread public void run
() ...Start running - Any Runnable object can wrap a thread around
itself - class Server implements Runnable Thread t
Server () t new Thread(this) . - public void run () ...Start running
- Thread control Thread.start(), Thread.stop()
135Manipulation of Current Thread
- // CurrentThreadDemo.java
- class CurrentThreadDemo
- public static void main(String arg)
- Thread ct Thread.currentThread()
- ct.setName( "My Thread" )
- System.out.println("Current Thread "ct)
- try
- for(int i5 igt0 i--)
- System.out.println(" " i)
- Thread.sleep(1000)
-
-
- catch(InterruptedException e)
- System.out.println("Interrupted.")
-
-
- Run
- Current Thread ThreadMy Thread,5,main
- 5
136Creating new Thread...
- // ThreadDemo.java
- class ThreadDemo implements Runnable
-
- ThreadDemo()
-
- Thread ct Thread.currentThread()
- System.out.println("Current Thread "ct)
- Thread t new Thread(this,"Demo Thread")
- t.start()
- try
-
- Thread.sleep(3000)
-
- catch(InterruptedException e)
-
- System.out.println("Interrupted.")
-
- System.out.println("Exiting main thread.")
-
137...Creating new Thread.
- public void run()
- try
- for(int i5 igt0 i--)
- System.out.println(" " i)
- Thread.sleep(1000)
-
- catch(InterruptedException e)
- System.out.println("Child interrupted.")
- System.out.println("Exiting child
thread.") -
- public static void main(String args)
- new ThreadDemo()
-
-
- Run
- Current Thread Threadmain,5,main
- 5
- 4
- 3
138Thread Priority...
- // HiLoPri.java
- class Clicker implements Runnable
- int click 0
- private Thread t
- private boolean running true
- public Clicker(int p)
-
- t new Thread(this)
- t.setPriority(p)
-
- public void run()
-
- while(running)
- click
-
- public void start()
- t.start()
- public void stop()
- running false
139...Thread Priority
- class HiLoPri
-
- public static void main(String args)
-
- Thread.currentThread().setPriority(Thread.MA
X_PRIORITY) - Clicker Hi new Clicker(Thread.NORM_PRIORIT
Y2) - Clicker Lo new Clicker(Thread.NORM_PRIORIT
Y-2) - Lo.start()
- Hi.start()
- try Thread.sleep(10000)
- catch (Exception e)
- Lo.stop()
- Hi.stop()
- System.out.println(Lo.click " vs. "
Hi.click) -
-
- Run1 (on Solaris)
- 0 vs. 956228
- Run2 (Window 95)
140Threads Need Synchronization
- Server instances lock themselves at method-level
- class Buffer // synchronize on buffer instance
public synchronized void put (int i) ... - public synchronized int get () . void safe () .
- Client instance locks a server object before
using it - synchronized (array_to_sort) ..... wait() //
within synchronized methodnotify() - notifyall() // wake up from a wait
141Monitor model (for Syncronisation)
Method 1
Method 2
Key
Block 1
Threads
Monitor (synchronised) solves race-condition
problem
142Threads Synchronisation...
- // Synch.java race-condition without
synchronisation - class Callme
- // Check synchronized and unsynchronized
methods - / synchronized / void call(String msg)
-
- System.out.print(""msg)
- try Thread.sleep(1000)
- catch(Exception e)
- System.out.println("")
-
-
- class Caller implements Runnable
-
- String msg
- Callme Target
- public Caller(Callme t, String s)
-
- Target t
- msg s
143...Threads Synchronisation.
- public void run()
- Target.call(msg)
-
-
- class Synch
- public static void main(String args)
- Callme Target new Callme()
- new Caller(Target, "Hello")
- new Caller(Target, "Synchronized")
- new Caller(Target, "World")
-
-
- Run 1 With unsynchronized call method (race
condition) - HelloSynchronizedWorld
-
-
- Run 2 With synchronized call method
- Hello
- Synchronized
144Queue (no inter-threaded communication)...
- // pc.java produce and consumer
- class Queue
- int n
- synchronized int get()
-
- System.out.println("Got "n)
- return n
-
- synchronized void put(int n)
- this.n n
- System.out.println("Put "n)
-
-
- class Producer implements Runnable
-
- Queue Q
- Producer(Queue q)
-
- Q q
145Queue (no inter-threaded communication)...
- public void run()
-
- int i 0
- while(true)
- Q.put(i)
-
-
- class Consumer implements Runnable
-
- Queue Q
- Consumer(Queue q)
-
- Q q
- new Thread( this, "Consumer").start()
-
- public void run()
-
- while(true)
- Q.get()
146...Queue (no inter-threaded communication).
- class PC
-
- public static void main(String args)
-
- Queue Q new Queue()
- new Producer(Q)
- new Consumer(Q)
-
-
- Run
- Put 1
- Got 1
- Got 1
- Got 1
- Put 2
- Put 3
- Got 3
- C
147Queue (interthread communication)...
- // PCnew.java produce-consumenr with interthread
communication - class Queue
-
- int n
- boolean ValueSet false
- synchronized int get()
-
- try
-
- if(!ValueSet)
- wait()
-
- catch(InterruptedException e)
-
-
- System.out.println("Got "n)
- ValueSet false
- notify()
- return n
148Queue (interthread communication)...
- synchronized void put(int n)
-
- try
- if(ValueSet)
- wait()
-
- catch(InterruptedException e)
- this.n n
- System.out.println("Put "n)
- ValueSet true
- notify()
-
-
- class Producer implements Runnable
-
- Queue Q
- Producer(Queue q)
-
- Q q
149Queue (interthread communication)...
- public void run()
-
- int i 0
- while(true)
- Q.put(i)
-
-
- class Consumer implements Runnable
-
- Queue Q
- Consumer(Queue q)
-
- Q q
- new Thread( this, "Consumer").start()
-
- public void run()
-
- while(true)
- Q.get()
150...Queue (no interthread communication).
- class PCnew
-
- public static void main(String args)
-
- Queue Q new Queue()
- new Producer(Q)
- new Consumer(Q)
-
-
- Run
- Put 0
- Got 0
- Put 1
- Got 1
- Put 2
- Got 2
- Put 3
- Got 3
- Put 4
151Deadlock...
- // DeadLock.java
- class A
-
- synchronized void foo(B b)
-
- String name Thread.currentThread().getName
() - System.out.println(name " entered
A.foo") - try
-
- Thread.sleep(1000)
-
- catch(Exception e)
-
-
- System.out.println(name " trying to call
B.last()") - b.last()
-
- synchronized void last()
-
152Deadlock...
- class B
-
- synchronized void bar(A a)
-
- String name Thread.currentThread().getName
() - System.out.println(name " entered
B.bar") - try
-
- Thread.sleep(1000)
-
- catch(Exception e)
-
-
- System.out.println(name " trying to call
A.last()") - a.last()
-
- synchronized void last()
-
153...Deadlock.
- class DeadLock implements Runnable
- A a new A() B b new B()
- DeadLock()
- Thread.currentThread().setName("Main
Thread") - new Thread(this).start()
- a.foo(b)
- System.out.println("Back in the main
thread.") -
- public void run()
- Thread.currentThread().setName("Racing
Thread") - b.bar(a) System.out.println("Back in the
other thread") -
- public static void main(String args)
- new DeadLock()
-
-
- Run
- Main Thread entered A.foo
- Racing Thread entered B.bar
154Threads in Action...Cooperative threads - File
Copy
reader() - - - - - - - - - - lock(buffi) read
(src,buffi) unlock(buffi) - - - - - - - - -
-
writer() - - - - - - - - - - lock(buffi) writ
e(src,buffi) unlock(buffi) - - - - - - - -
- -
buff0
buff1
Cooperative Parallel Synchronized Threads
155Threads in Action... Multithreaded Server
Server Process
Client Process
Server Threads
Client Process
User Mode
Kernel Mode
Message Passing Facility
156A Look Inside the Java Platform
Applets and Applications
Java Base API Java Base Classes
Java Standard Extension API Java Standard
Extension Classes
The Java Base Platform (in black)
Java Virtual Machine
Porting Interface
Network
Java on a Browser
Java on a Desktop OS
Java on a Smaller OS
Java on JavaOS
157Java Applications!
- Java applications are now available
- Cost of manfg zero, cost of distribution zero,
cost of marketing zero! - Hot Java is lean - loads everything else from the
net. - Java itself is small - 40k to 225k
- New class of small machines will emerge
- Java on cellular phones, credit cards, washing
machines, and everywhere ?
158Universal Interface
Web Servers with JAVA applications
Internet
Clients running any OS on any platform
159Java on my platform ?
- Sun (SPARC) ftp//java.sun.com
- Sun(x86) ftp//xm.com/pub/
- IBM(Aix, OS/2)ftp//ncc.hursley.ibm.com/javainfo
- DEC(Alpha OSF/1) http//www.gr.osf.org8001/projec
ts/web/java/ - SGI http//liawww.epfl.ch/simon/java/irix-jdk.htm
l - HP http//www.gr.osf.org8001/projects/web/java
- Linux http//www.blackdown.org
- AT T http//www.gr.osf.org8001/projects/web/jav
a - Windows 3.1 http//www.alphaworks.ibm.com
160Java Development Tools (Present and Planned)
161Suns Java WorkShop
- JDK
- Compiler and runtime environment
- Class Libraries
- Documentation
- javadoc - Automated Documentation
- Takes comments and converts to HTML
- IDE Visual Java, and integrated tools, JavaBeans
- Other Products and API JavaHelp, Java Card, Java
Blend, JavaOS, Java Mail, Java Management, Java
Electronic Commerce Framework - Java Enterprise API Java Naming and Directory
Interface, Java IDL, JDBC, RMI and Object
Serialization
162Symantec Cafe 1.0 (Released)
- Full IDE for Windows 95/NT
- Graphic Development Tools
- Two Compilers
- Debugger
- Class Browser
163Microsoft Jakarta (Planned)
- Visual C type interface
- Will Support ActiveX/COM
- Internet Explorer 3.0 will have Just-In-Time Java
compiler
164Borland JBuilder
- Visual RAD workbench for maximum productivity.
- Rapid Application Development (RAD) and Open
Component Architecture patterned after Delphi. - 100 JavaBean components, with source code, for
drag-and-drop applications. - Beans Express--easiest way to create
industry-standard Java-Bean components. - DataExpress -- the fastest way to build business
and database appplications. - Borland DataGateway for Java connectivity to all
major database servers. - Multi-tier applications with integrated RMI and
CORBA. - Versions Standard, Professional, Client/Server
165Challenges Possible Directions
- Performance
- AWT - need better GUI!
- Maintaining Interoperability
- Security - current restrictions limit what can be
done - Native Compilers
- Is Portability that Important?
166Comments
- Java is a fun and easy programming language
- Portability Mediocrity?
- Java will become a programming language of
choice, but may take on a final form that will
surprise many!
167JDBC
- Java API for Relational Databases
- Being standardized by all major players
168Javascript and Java (Preview)
- Javascript can control Java applets
- Static data accessible as properties of applet
- var i Bank.Account.count
- Public methods invocable on Java instances
- Provided those instances are accessible through
the Applet - Applet is accessible through document
- document.applet_Name_Attribute.do_S