Professional Documents
Culture Documents
SL-277
Module 1
Objectives
• Identify differences between JDK™ 1.1 and JDK 1.2
Security Enhancements
• External policy files
JavaBeans Components
• Overview of JavaBeans™ Component Model
• The JavaBeans Activation Framework
• The InfoBus™
• Enterprise JavaBeans
System Enhancements
• Improved multithreading
• More efficient garbage collector
• Improved memory usage
• Just-in-time compilers
• Rewritten native libraries
System Enhancements
• Serialization enhancement
• Input method framework
• Java Debugger API
• Reference objects
Miscellaneous Enhancements
• JDBC 2.0
• Support for SQL 3.0
• Audio enhancements
• Package version control
• JAR improvements
Miscellaneous Enhancements
• Java IDL support (CORBA)
• Java standard extensions
• Reflection enhancements
Module 2
Objectives
• Discuss the goals of security
• Compare JDK 1.1 and JDK 1.2 software security
• Identify new classes and concepts
• Policy objects
• Permission and permissions objects
• Access controller
• Protection domain
Security Goals
• Protection from harmful code
• Viruses
• Trojan horse programs
• Protection from system intrusion
• Hidden private data
• Authentication of entities
• User IDs and passwords
• Digital signatures
Security Goals
• Authorization
• Permitted activities for some authenticated entity
• Containment
• Enforceable boundaries
• The sandbox security model
• Non-repudiation
• No denying involvement in a transaction
../images/chapter2/class1.jpg
Permissions
• The Permission class
• Represents access to a particular resource
• Creates subclasses for specific types
• Included permissions
• java.io.FilePermission
• java.lang.RuntimePermission
• java.net.SocketPermission
Permissions
• Permission format
• All permissions have some target, the resource being
controlled
• Many also have a list of actions
• Examples
FilePermission fp = new
FilePermission("/tmp/-","read, write");
RuntimePermission rp = new
RuntimePermission("exit");
SocketPermission sp = new
SocketPermission("www.foo.com","accept");
Permissions
• The implies(Permission p) method
• All permissions must implement this method
• It determines logical implications
• Example
FilePermission abc = new
FilePermission("*.txt","read");
FilePermission xyz = new
Permissions
FilePermission("cool.txt","read");
abc.implies(xyz) == true
xyz.implies(abc) == false
Policies
• Policy objects
• They are queried at runtime for the permissions
granted a particular CodeSource
• There can only be one in existence at a time, but it can
change during runtime
Policy currentPolicy = Policy.getPolicy();
Permissions granted =
currentPolicy.getPermissions(someCodeSource);
Policies
• Policy files
• User configurable series of grant statements
• No involvement in making decisions
• No limit on the number of policy files; they are all
read to create the system policy
• Grant statements
grant [codebase "<URL>"][signedBy <alias>"]{
permission [permission
class]["target"],["actions"];
};
Policies
• Two default policy files
• The system policy file, java.policy
• The user policy file, .java.policy
• Property expansion in policy files
• All ${XXX} tokens are expanded to match some
system property
grant signedby "Godzilla" {
permission java.io.FilePermission
${user.home}${/}"*", "read";
};
Security Management
• The AccessController entity
• Asks current policy for permission to access some
controlled resource
• Is used by the security manager to check system
resources
• A file access example
FilePermission fp = new
FilePermission("/data/money.dat","read");
try{
AccessController.checkPermission(fp);
}catch(AccessControlException){...}
Security Management
• How the AccessController works
• Starting with the caller's domain, checks each class
domain on the stack
• Makes sure all class domains are granted permission
• Is successful if all domains have no exceptions or a
privileged block
for(i = firstDomain; i >=0; i++){
if(domain i does not have permission)
throw newAccessControlException("Denied");
if(domain i is priveleged)
return;
}
return;
Security Management
• Privileged blocks
• Indicates a stopping point for the
AccessController stack trace
• Allows invoked, privileged code to perform some
action on behalf of calling unprivileged code
...
AccessController.doPrivileged(new
PrivilegedAction() {
public Object run() {
System.loadLibrary("awt");
return null; // could return a property value
}
});
Security Management
• The SecurityManager
• No longer an abstract class
• Applications are subject to sandbox
• Load the system security manager automatically
and/or specify policy files
• New class path for untrusted, but local, code
java -Djava.security.manager MyApp
java -Djava.security.policy = my.policy MyApp
java -Djava.security.policy == my.policy MyApp
java -Djava.class.path=\somePath MyApp
NewABCSecurityManager.java
Example
import java.security.*;
public class NewABCSecurityManager extends
SecurityManager {
../images/chapter2/signing.gif/
PublicKey pk = ...;
sig.initVerify(pk);
sig.update(message.getBytes());
byte [] signature = ...;
if(sig.verify(signature)){...}
../images/chapter2/verifying.gif
../chapter2/ptmain.gif
arrow_d.gif
ptnext.gif
arrow_d.gif
ptadd.gif
Module Summary
• JDK 1.2 offers fine-grained access control with
permissions, policies, and protection domains.
• Protection domains are composed of a CodeSource (a
URL and an array of public keys) and the set of
Permissions granted.
• Access control is handled by the AccessController.
• Applications can be constrained in the same sandbox as
applets.
• New security tools enhance security control.
Module 3
Objectives
• Explain motivations for JFC
• Discuss simple Swing components
Overview of JFC
• Motivations for JFC's creation
• Limited widget set in AWT
• Increase flexibility of UI code
• Configurable look and feel of components
• Increase graphics and rendering capabilities
• Need for accessibility support – Screen magnifiers
and Braille support
• Support for drag and drop
ListCellRenderer
1 public class MyCellRenderer extends JLabel implement ListCellRenderer{
2
3 public Component getListCellRendererComponent(JList list, Object o
4 int index, boolean selected, boolean focus){
5
6 setFont(new Font("serif",Font.BOLD,24));
7 setBackground(selected ? Color.blue : Color.white);
8 setForeground(selected ? Color.white : Color.blue);
9 return this;
10 }
11 }
12
Introduction to MVC
What is MVC?
• Has a design pattern with three cooperating objects
• Model
• View
• Controller
• Is often used in GUI design
• Allows control over appearance, data sources, and
event responses in a flexible fashion
Introduction to MVC
The model
• Design pattern with three cooperating objects
• Underlying representation
• Definition of how something works
• For example, a checkbox model might indicate a true
or false state regardless of how it appears to the user
• Encapsulated in Swing by interfaces (ButtonModel,
ListModel,and so on)
• Found only in components using data
Introduction to MVC
The view
• Visual representation
• Definition of how something appears
• Separate entity from the model
Introduction to MVC
• The controller
• Specifies how to handle events and user input
• Acts as a conduit between the model and view when
changes occur in either
• Uses event handlers for the controller role
• The delegate
• Coordinates between the view and controller
• Combines these two into one unit called the delegate
• Is encapsulated in the XXXUI classes
Introduction to MVC
• MVC demonstration
• Create one model for a JList and JComboBox to
share
• Use the DefaultListModel for each
Introduction to MVC
Create one model for a JList and JComboBox to share
1 class FontListModel extends DefaultListModel implements
2 ComboBoxModel{
3 private String [] list =
4 Toolkit.getToolkit().getFontList();
5 private Object cv;
6 public int getSize(){
7 return list.length;}
8 public Object getElementAt(int index){
9 return list[index];}
10 public void setSelectedItem(Object o){
11 cv = o; }
12 public Object getSelectedItem(){
13 return cv;}
14 }
15 FontListModel model = new FontListModel();
16 JList list = new JList(model);
17 JComboBox box = new JComboBox(model);
path.quadTo(100.0f,150.0f,200.0f,200.0f);
path.closePath();
g2d.setColor(Color.blue);
g2d.fill(path);
}
images/chapter3/bezier.gif
g2d.setComposite(alpha);
g2d.drawImage(im, 75, 25, this);
...
images/chapter3/alpha1.gif
images/chapter3/alpha2.gif
images/chapter3/dnd.gif
DragGestureRecognizer dgr =
source.createDefaultDragGestureRecognizer
(component, DnDConstants.ACTION_COPY,
dragSourceListener);
Component Action
JButton Click
JCheckBox Click
JRadioButton Click
AWT Enhancements
Multithreaded event queue
• The event-dispatching thread handles events
(actionPerformed()) and rendering (paint()).
• Operations can interfere with the event-dispatch thread
and vice-versa.
• invokeLater(Runnable r) and
invokeAndWait(Runnable r) solve this interference.
• Developers can have specific code run inside the event-
dispatching thread.
AWT Enhancements
class ABC implements Runnable{
public void run(){ // some intensive work }
}
//invokeLater(Runnable r)
Runnable r = new ABC();
SwingUtilities.invokeLater(r); // don't wait
//around
//invokeAndWait(Runnable r)
Runnable r = new ABC();
SwingUtilities.invokeAndWait(r); // wait until
//done
AWT Enhancements
• Cursors
• All the basic cursors are provided with JDK software
• Cursors are customarily 16x16 or 32x32 pixels in size
• A custom cursor
Toolkit t = Toolkit.getDefaultToolkit();
Image im = t.getImage("copy.gif");
Cursor copyCursor = t.createCustomCursor(im,
new Point(0,0), "copy");
this.setCursor(copyCursor);
AWT Enhancements
• Keyboard navigation
• Mnemonics are included with Swing
• AbstractButton defines the get/setMnemonic
methods
• The platform-specific accelerator key (Alt, Ctrl, Meta
and so forth) is used
AWT Enhancements
• KeyStroke
• Represents a key being typed on the keyboard
• Can contain a modifier if needed (Alt, Ctrl, Meta, and
so on)
• Defines high-level action events
• Does not trap every keystroke
• KeyStroke example
KeyStroke ks = KeyStroke.getKeyStroke('g');
rb1.registerKeyboardAction(actionListener, ks,
JComponent.WHEN_IN_FOCUSED_WINDOW);
Module Summary
• Swing is the future of Java GUIs.
• Swing provides modern, configurable, and accessible
controls.
• 2-D Graphics greatly improve the imaging and
rendering capabilities of Java technology.
• Drag and drop brings Java technology into the modern
UI world.
• Java accessibility is essential for continued success with
user with disabilities.
Module 4
Collections
Objectives
• Define collections
• List advantages of the Collections API
• Explain design goals
Introduction to Collections
• What are collections?
• Individual objects that represent a group of objects
• Containers
• Examples of collections
• Arrays
• Vector
• Hashtable
Advantages of Collections
• Little effort to learn new API
• Little effort to implement API
• Leads to reusability
• Interoperability between different APIs
Design Goals
• Small API
• Easy to learn
• Reasonably powerful
• Works with earlier collections
• Easily extensible
Basic Implementations
Abstract base classes
• Implements corresponding interface
• Extends to create implementations
• Provides minimal implementation
• AbstractCollection
• AbstractSet
• AbstractMap
• AbstractList
• AbstractSequentialList
Basic Implementations
HashSet
• Extends AbstractSet
• Does not allow duplicate elements
• Has no guarantee of order
• Is not thread-safe
HashSet hs = new HashSet();
Integer x = new Integer(1);
Integer y = new Integer(2);
hs.add(x);
hs.add(y);
hs.add(x); // not added
int size = hs.size(); // 2
Object [] stuff = hs.toArray();
Basic Implementations
HashMap
• Extends AbstractMap
• Does not allow duplicate keys
• Has no guarantee of order and is not thread-safe
HashMap hm = new HashMap();
Integer x = new Integer(1);
Integer y = new Integer(2);
hm.put("First", x);
hm.put("Second", y);
hm.put("First", x); // not added
hm.put("Third", x); //added
int size = hs.size(); // 3
hs.containsKey("First"); //true
Basic Implementations
ArrayList
• Extends AbstractList
• Is resizable dynamically
• Acts like Vector, but unsynchronized
• Provides random access and not thread-safe
HashSet set = new HashSet();
set.add("Bluejay");
set.add("Oriole");
set.add("Sparrow");
ArrayList list = new ArrayList(set);
int size = list.size(); //3
list.contains("Bluejay"); // true
list.ensureCapacity(25);
Basic Implementations
LinkedList
• Extends AbstractSequentialList
• Is resizable dynamically
• Provides sequential access
• Is not thread-safe
LinkedList list = new LinkedList();
list.add("Bluejay");
list.addFirst("Oriole");
list.addLast("Sparrow");
String s = list.getFirst(); // returns "Bluejay"
String t = list.getLast(); // returns "Sparrow"
Iterators
Iterator
• Represents an iteration over a collection
• Replaces Enumeration for collections
• Differs from Enumeration
• Allows removal of elements from collection
• Has improved method names
hasNext() // true if there is a nextelement
next() // returns next element
remove() // removes last element retrieved
(optional)
Iterators
ListIterator
• Extends Iterator
• Allows traversal in either direction
• Can optionally support adding/removing
• Adds some new methods:
asPrevious() // true if there is a
//previous element
previous() // returns previous element
set(Object o) // replaces last element
//retrieved - optional
add(Object o) //adds new element - optional
Iterators
ListIterator example
LinkedList list = new LinkedList();
list.add("Bluejay");
list.add("Oriole");
ListIterator iterator = list.listIterator();
iterator.add("Sparrow");
while(iterator.hasNext()){
System.out.println(iterator.next());
}
• The output
• Bluejay
• Sparrow
• Oriole
Anonymous Implementations
The Collections class
• Consists only of static methods
• Contains algorithms for general operations
• Has manipulations
• binarySearch(List list, Object element)
• copy(List listOne, List listTwo)
• max(Collection coll)
• min(Collection coll)
• sort(List list)
Anonymous Implementations
• Unmodifiable collections
unmodifiableCollection(Collection coll)
unmodifiableXXX(XXX xxx)
• Synchronized wrappers
• Arrays
• Static methods for copying, sorting, and searching
arrays
• Methods that convert arrays to lists
Anonymous Implementations
• Collections examples
• Arrays examples
int [] array = {1,4,2,5,3};
Arrays.sort(array); // now 1,2,3,4,5
int index = Arrays.binarySearch(array, 2) // 1
Synchronized Wrappers
Details of synchronized wrappers
• Gives collections thread safety
• Has iterations which must be done in a synchronized
block
• Must access through the new version
Synchronized Wrappers
Example
LinkedList list = new LinkedList(); // not
thread-safe
list.add("Bluejay");
list.add("Oriole");
list.add("Sparrow");
List safeList =
Collections.synchronizedList(list);
synchronized(safeList){
ListIterator iterator = safeList.listIterator();
...
}
list.addFirst("Magpie"); // NO!
...
Comparing Collections
Comparable
• Has an interface implemented by specific classes
• Provides natural ordering
• Has its functionality in the compareTo(Object o)
method
• Supports some implementing classes: String, URL,
and Date
Comparing Collections
Comparator
• Interface implemented by specific classes
• Overrides any natural ordering
• Two methods
compare(Object one,Object two)
-1 = less than
0 = equals
1 = greater than
equals(Object o)
Comparing Collections
Comparator example
class AnyString implements Comparator{
public int compare(Object one, Object two){
String s = (String)one;
String t = (String)two;
return s.compareToIgnoreCase(t);
}
}
...
LinkedList list = new LinkedList();
list.add("Bluejay");
list.add("Oriole");
list.add("Sparrow");
Collections.sort(list, new AnyString());
Compatibility
• Changes to existing classes
• Vector implements List
• Hashtable implements Map
• Arrays.asList(someArray)
• Has backward compatibility
• someCollection.toArray()
• new Vector(someCollection)
• new Hashtable(someMap)
Compatibility
• Cross compatibility
• new LinkedList(Collection c)
• new HashSet(Collection c)
• new HashMap(Map m)
Module Summary
• New Collections API improve on basic types.
• Simple API allows for short learning curve.
• Built-in algorithms meet common needs.
• Extensible implementations meet advanced needs.
• There is wide-ranged compatibility.
Module 5
Objectives
• Describe RMI
• Build an RMI system
• Introduce activation
• Build an activation system
• Describe custom socket factories
• Introduce SSL support
Overview of RMI
What is RMI?
• Remote method invocation
• Distributed OO programming in Java technology
• Similar to RPC
• Different than CORBA and DCOM
• 100% Pure Java solution
Overview of RMI
What are the benefits?
• Simple to implement
• Transparent access to remote objects
• Distributed garbage collection
• No extra language to learn
• Ships with standard JDK distribution
Overview of RMI
Are there drawbacks?
• Static binding of objects
• Not as flexible as CORBA
• Not persistent by default
• Latency introduced to the system
images/chapter5/proto_1.gif
images/chapter5/proto_3.jpg
Module Summary
• RMI provides a distributed, Java technology solution.
• Activation is now provided, increasing performance.
• Building an RMI solution is fairly simple.
• Socket factories provide customized control.
• SSL support is provided by a standard interface.
• Third-party vendors provide SSL implementations.
Module 6
JavaBeans Components
Objectives
• Define the JavaBean component model
• Introduce model characteristics
• Explain the JavaBeans Activation Framework
• Describe the InfoBus
• Review Enterprise JavaBeans
JavaBeans Defined
• What is a JavaBean?
• A reusable software component that can be
manipulated visually in a builder tool
• A cross-platform, cross-builder tool, flexible,
component model for Java technology
• Why use JavaBeans components?
• They offer true reusability in a dynamically
introspective fashion.
• They give Java technology a modern component
architecture for flexible solutions.
JavaBeans Defined
• What does the model define?
• Java technology software components
• How the components interact
• Standardized "hooks" for builder tool compatibility
JavaBeans Defined
• Design goals
• Simple to learn, design, and use
• Leverages existing Java technology features
• Can be built with builder tools and manually
• Extensible enough to build complex solutions
JavaBeans Characteristics
• Introspection
• Is based on Java Reflection API
• Has automatic discovery of a Bean
• Learns the interface
• Has standard "design patterns" that make this simple
• Enables more complex control via a BeanInfo
JavaBeans Characteristics
• Properties
• Represent a component's state
• Are defined with "getter" and "setter" methods
• Have three styles of properties – Simple, Bound, and
Constrained
JavaBeans Characteristics
• Events
• Are based on standard event model
• Allow for registration of listeners
• Fire methods in a standard fashion
• Offer Bean communication
• Provide an extremely flexible solution
JavaBeans Characteristics
• Customization
• Allows for simple control of a Bean's properties
• Has two GUI mechanisms for customization –
Property Sheets and Customizers
• Is completely configurable
JavaBeans Characteristics
• Persistence
• Uses Java Serialization API
• Allows for a customized bean to be stored
• Has a mechanism that is customizable
• Distributed capabilities
• Is fully capable of working with distributed APIs –
RMI, JDBC, and CORBA; for example, Enterprise
JavaBeans
• Component delivery
• Packages Beans in JAR files
Samples of Characteristics
• Properties
public void setMonster(Monster m){...}
public Monster getMonster(){...}
• Event sources
public void addMonsterListener(MonsterListener
m){...}
public void
removeMonsterListener(MonsterListener m({...}
...
Samples of Characteristics
• Other characteristics
• Must be public classes
• Must have a no-arg constructor
• Must contain private data and public methods
JAF Architecture
• DataSource interface
• Abstracts an object containing data
• Provides streams to access data
• Stores a string defining the MIME type
• Provides two implementations
FileDataSource
URLDataSource
JAF Architecture
• Implementing DataSource
• Is responsible for typing the data
• Provides various types associations
JAF Architecture
• DataHandler class
• Provides an interface to data in various formats and
sources
• Manages stream-to-String conversions
• Provides access to command associated with data
JAF Architecture
• DataHandler implements Transferable
• Allows data to be used in AWT data transfer
operations
• Uses a DataContentHandler associated with the
MIME types
• Has DataHandler encapsulate this access
JAF Architecture
• CommandMap class
• Retrieves the correct command object to operate on
the data
• Stores some or all of the mapping in a .mailcap file
• Enables the .mailcap fileto work with a mime.types
file
The InfoBus
What is the InfoBus?
• Standardized communication for Java technology
solutions
• Finding the data
• Representing the data
• Exchanging the data
• Doing all at runtime
• A technology that works with applets, JavaBean
components, servlets, and so on
The InfoBus
• Better solution than using scripting to "bind" objects
• Developed by Lotus, licensed by Sun for the JDK
software
• Distributed as a Java Standard Extension
The InfoBus
• Characteristics of the InfoBus
• Works within one VM
• Provides hooks for intra-VM communication
• Has a standard interface to access data
• Dynamically informs interested code of new data
• Is 100% Pure Java
• Is vendor-independent
• Is free
The InfoBus
• How does the InfoBus work?
• Finds the data
• Defines interfaces for representing data
• Defines interfaces for accessing data
• Transfers the actual data directly between the
components
The InfoBus
Diagram of the InfoBus
images/chapter6/model.gif
Enterprise JavaBeans
• What are Enterprise JavaBeans?
• Defines a component model for distributed
components
• Supports server-side components
Enterprise JavaBeans
• Server components
• Runs application components on a server
• Simplifies moving the logic to the server
• Implements a set of automatic services
• Is non-visual
• Is CORBA compatible
Enterprise JavaBeans
• Benefits of multitier solutions
• Increases scalability
• Improves preformance
• Heightens reliability
• Increases flexibility
• Eases system load
• Encapsulates business rules
Enterprise JavaBeans
• Component execution systems
• Provides runtime services for EJB components –
Threading, Transactions, State, and Sharing
resources
• Is designed to be implemented by vendors
• Is often an Object Transaction Monitor (OTM)
• Has EJB Servers
Enterprise JavaBeans
• Goals of EJB
• Become the standard enterprise component model
for Java technology
• Have toolable server-side components
• Be easy to develop as complexities are abstracted
• "Write Once, Run Anywhere"™
• Have the life cycle of EJB components addressed by
architecture
• Be CORBA compatible, which offers interoperability
EJB Roles
• EJB provider
• Is usually an application domain expert
• Is not expert in system-level programing –
Transactions, concurrency, security, and distribution
• Defines business rule architecture
EJB Roles
• Application assembler
• Composes applications using EJB
• Only recognizes interfaces, not implementations
• Often designs client-side GUIs as well
• Deployer
• Is responsible for EJB components and their
containers
• Adapts EJB components to specific logical
environements
• Modifies the attributes of an EJB component
JAVA Development Kit Software 1.1–1.2 Enhancements -37 of 56
Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services November 1998
Sun Educational Services
EJB Roles
• Server provider
• Specialist in distributed object management
• Usually an OS, database, or middleware vendor
• Creates the containers for EJB components
• Allowed to create specialized containers
• Bridges to existing application environments
• Has object–relational data mapping
EJB Roles
• System administrator
• Monitors a complete, running system
• Uses management tools to maintain the system
images/chapter6/runtime.gif
images/chapter6/app_serv.gif
javax.ejb.deployment.SessionDescriptor
javax.ejb.deployment.EntityDescriptor
Module Summary
• JavaBeans are 100% Pure Java components.
• Components provide true reusability.
• The JAF automates MIME type binding to commands.
• The InfoBus allows transparent communication
between components and applets.
• EJB changes server applications radically.
• EJB is the future of distributed Java technology
solutions.
Module 7
System Enhancements
Objectives
• Discuss improvements in threading model
• Explain improvements in memory usage
• Talk about just-in-time compilers
• Explain the rewritten native libraries
• Describe serialization enhancements
Threading Enhancements
• Solaris native threads option
• In JDK 1.1, Solaris threading was user-level (green
threads)
• In JDK 1.2, native Solaris threads were used
• Native threads enable the use of multiple CPUs and
better performance
Threading Enhancements
• Faster synchronized methods
• Improved monitor design
• Run almost as fast as normal methods now
Memory Management
• The heap
• One heap per VM
• Created on VM start-up
• Runtime memory area for objects and arrays
• Might expand, never contracts
• Improved heap performance
• Java heap is managed automatically by the GC
• Fewer "heap locks" are required in VM
• Decreases time of garbage collection process
Memory Management
• The contant pool and strings
• One per class or interface
• Created when a class or interface is loaded
• In JDK 1.2, strings are shared among classes
• Reduces memory consumption
Just-in-Time Compilers
• What is a JIT?
• Converts bytecode to machine code
• Stores machine code in a runtime cache
• Does not create executable files
• Forces code to run much faster
Just-In-Time Compilers
• JIT is now included with JDK software
• Has default runtime environment
• Can be turned off or replaced with another JIT
java -Djava.compiler=NONE
java -Djava.compiler=OtherJIT
Serialization Enhancements
• Added optional replace and resolve methods
• Object writeReplace()
• Object readResolve()
• Both methods can have any access modifier
• If provided in class, methods are called automatically
• The objects returned are the "new" objects
Reference Objects
• What is a reference object?
• Encapsulates a normal Java reference
• Gives user-control over the garbage collector
• Keeps objects eligible for collection "alive"
• Why are they useful?
• References objects with different strengths
• Allows flexible control over memory management
Reference Objects
• Has reachability strengths
• Strongly reachable (normal)
• Softly reachable; might be garbage collected if
memory is low
• Weakly reachable
• Will be collected as garbage
Reference Objects
• Phantomly reachable
• Will be finalized, but not removed
• Performs specific clean-up
• Informs the program
• Must create a reference queue
Reference Objects
• Reference queues
• Data structure where reference objects can be stored
• Programs used by the garbage collector
• Program which places reference objects into the
queue
• Program which can poll queue for reclamation time
Module Summary
• Threading has improved, especially on Solaris™
platforms.
• Memory is better managed.
• Strings are shared between different classes.
• JIT compilers increase performance.
• Serialized objects can be replaced in streams.
• The IMF internationalizes Java technology better.
• Reference objects allow user control of memory.
Module 8
Miscellaneous Enhancements
Objectives
• List JDBC 2.0 additions
• Introduce audio enhancements
• Describe package version control
• Explain JAR improvements
• Introduce the Java IDL classes
• Describe Java Standard extensions
• Describe reflection enhancements
Introducing JDBC
• What is JDBC?
• Java Database Connectivity
• Transparent access to various databases
• Implementations provided by vendors – Oracle,
Sybase, and any ODBC database
Introducing JDBC
• How does JDBC work?
• Is based on interfaces, providing consistent types
• Maps calls to database by a driver
• Has vendors write the drivers
• Is used by developers to communicate with the
drivers via JDBC
Introducing JDBC
• The DriverManager
• Class providing access to drivers
• Drivers which register with DriverManager when
loaded
• Developer’s call to getConnection() to connect
• Statement objects which wrap communication to
DB
• ResultSet objects which hold results of queries
JDBC Step-by-Step
1. Load the vendor's driver.
Class.forName("com.zippy.CoolDBDriver");
2. Create a URL string to the driver.
String url = "jdbc:zippy://hostname:1500/CoolDB";
3. Get a connection to the database.
Connection c = DriverManager.getConnection(url);
JDBC Step-by-Step
4. Create a statement.
Statement s = c.createStatement();
5. Send SQL command.
String command = "SELECT * FROM Names";
ResultSet rs = s.executeQuery(command);
JDBC Step-by-Step
6. Process the results.
while(rs.next()){
System.out.println(rs.getString(1));
System.out.println(rs.getInt(2));
}
7. When done, close connection.
c.close();
• Updatable
Audio Enhancments
• New formats supported – WAV, AIFF, and MIDI
• New sound engine
• Better sound quality
• Static newAudioClip(URL) method in Applet
• Allows applications to easily use an AudioClip
Version Control
• Runtime environment discovery
• Applications can now determine the version of JDK,
JRE, and packages
• Discovery is done via system properties
• New class, Package, was added to support discovery
Jar Enhancements
• JAR tool support for updating archives
jar cvf MyJar.jar First.class
JavaIDL
• CORBA classes part of core JDK software
• org.omg packages
org.omg.CORBA
org.omg.CosNaming
org.omg.portable
• Simple ORB included in JDK software
• Only provides a naming service
• Compliant with CORBA 2.0 portability specs
JavaIDL
• The transient name service daemon
• Is tnameserv
• IDL compiler provided as separate download
• Is idltojava
• Uses official OMG Java-to-IDL mapping
• Supports the TIE protocol (delegation)
Adding Extensions
• Installed extensions
• Extracted to $JAVA_HOME/lib/ext
• Installed native libraries to
Solaris: $JAVA_HOME/lib/<arch>
Windows: $JAVA_HOME/bin
• Searched right after system classes
Adding Extensions
• Downloaded extensions
• Referenced via manifest files in another JAR file
• Specified by Class-Path field in manifest
Classpath: someJar.jar stuff/cool.jar
• Have "temporary" extensions
• Have no fixed location; loaded in memory
• Do not become installed extensions
Some Extensions
• JNDI
• JavaMail
• Enterprise JavaBeans
• Java Commerce
• JavaBeans Activation Framework
• InfoBus
• Java Help
Reflection Enhancements
• What is reflection?
• Allows runtime discovery of loaded class
information
• Class
• Superclass
• Methods
• Fields
• Constructors
Reflection Enhancements
• When is it used?
• JavaBeans
• RMI
• Any application needing runtime flexibility
Reflection Enhancements
• Security and reflection
Reflection Enhancements
• AccessibleObject
• Is a new class in JDK 1.2
• Is a superclass of all reflection classes
• Contains three methods to control and determine
access level
Reflection Enhancements
• ReflectPermission
• If set, allows setting of the accessible flag
• Gives the right to ystem code automatically
• Allows any method to be called (including private)
• Be careful!
Reflection Enhancements
• An access example
class CallMe{
private void method(){
// some senstive operations
}
}
class WatchThis{
...
Class clazz = Class.forName("CallMe");
Method m = clazz.getMethod("method", null);
m.setAccessible(true);
m.invoke(new CallMe(), null); // WORKS!
...
}
Module Summary
• JDBC is radically improved for flexibility.
• Result sets are scrollable and updatable.
• Batch processing of SQL commands was added.
• Audio has been expanded and improved.
• Packages can now be version controlled.
• JAR files can be updated.
• JAR files can be read and written within applications.
Module Summary
• Java IDL is now part of JDK software.
• Java Standard Extensions provide optional additions to
the JDK software.
• Access can now be controlled during reflection.
Module 9
Topics
Topics
• JavaSpaces
• Jini
• HotSpot VM
• Java Blend
Introducing JDBC
• What is JDBC?
• Java Database Connectivity
• Transparent access to various databases
• Implementations provided by vendors – Oracle,
Sybase, and any ODBC database
JavaSpaces
• Where will it be used?
• Workflow systems
• Trading services
• Auction-style systems
• Publish and subscribe systems
• Data distribution systems
Goals of JavaSpaces
• Only six major methods
• read()
• take()
• write()
• notify()
• readIfExists()
• takeIfExists()
• Most server code written by JavaSpace™ for you
Goals of JavaSpaces
• Unified interface
• Sharing, cooperating, and communicating objects all
via one simple interface
• Support for legacy code
• Works with CORBA, EJB, JDBC, and so on
• Utilize Java semantics
• Find objects via type
Goals of JavaSpaces
• Uses live objects, not just data
• Behavior and state can be stored
• Asynchronous
• No blocking during writing or reading
• Is handled for you by JavaSpaces
• Extensibility
• Can store data in RDBMS or ODBMS
Goals of JavaSpaces
• Transparent implementation
• Providers and requestors need not know details
• 100% Pure Java
• No native code is required
JavaSpaces Concepts
• The JavaSpace
• Holds entries
• Is accessible for writing and reading
• Entries
• Have typed objects implementing space.entry
JavaSpaces Concepts
• Manipulating entries
• Write creates a copy in the space
• Read returns a copy
• Take removes a copy
• Notify informs users when an entry is available
• Templates
• Use objects that have specific values set
• Involve only matching entries in read, take, or notify
JavaSpaces Concepts
• Distributed events
• Basis for notify operations
• Transactions
• JavaSpaces provides atomic control
• Either all operations in a transaction succeed, or none
do
Jini
What is Jini?
• Was inspired by Bill Joy
• Enables "spontaneous networking" of anything
• Uses hardware and software in a sort of "network
communion"
• Makes using networks and devices easy
• Has dynamic connections that allow networks to
automatically change
Jini Infrastructure
Discovery
• Defines how a service registers itself with a network
• Requires no prior knowledge of network
• When a device is plugged-in, sends a byte packet to
some port
• Announces its presence on a network which supports
Jini
Jini Infrastructure
• Lookup
• Is a "bulletin board" for network services
• Changes dynamically as services are added and
removed
• Listens on some port for new additions to the
systems
• Join
• Occurs after a successful discovery-join transaction
• Enables a device to upload information about itself to
network
Distributed Jini
• Leasing
• A device registers for a specific lease time
• Once this time expires, the device must renegotiate
• This allows for distributed garbage collection
• Distributed events
• Events carry an event number allowing for sequencing
• Allows learning if events were recieved out of order
• If events are lost, it can be discovered
Distributed Jini
• Transactions
• A transaction manager can be started by objects
• All participating objects register with the manager
• If any part fails, the manager rolls back all objects
• Maintains well-known state
• Network services
• JavaSpaces will play a large role in Jini
HotSpot VM
What is the HotSpot?
• Is the next-generation virtual machine
• Maintains the same rules as current VMs
• Was totally re-engineered with new technologies
• Provides much higher performance than current VMs
HotSpot Benefits
High performance
• References implemented as direct pointers
• Significantly faster thread synchronization
• Reduced code space and start-up time
• Faster method invocations
• Native-code speed
• Method-inlining when possible
• HotSpot "learns" how to make improvements
dynamically
HotSpot Benefits
• Improved garbage collection
• Faster object allocation
• More accurate object reclamation
• Radically decreases collection pauses
• New algorithm which provides less memory
fragmentation
• HotSpot detection
• Optimization focused on performance-critical code
JavaBlend
What is JavaBlend?
• Provides mapping between objects and database tables
• Enables automatic mapping, reducing complexity
images/chapter9/jbapps.gif
Module Summary
• JavaSpaces provides dynamic distrubution.
• Jini allows distributed VMs to work as one.
• Jini revolutionizes distributed systems.
• HotSpot solves Java technology performance problem.
• JavaBlend eases mapping objects to databases.
Collections ...............................................................................................................................4-1
Objectives ................................................................................................................................................. 4-2
Introduction to Collections .................................................................................................................... 4-3
Java Collections API ............................................................................................................................... 4-4
Advantages of Collections ..................................................................................................................... 4-5
Design Goals ............................................................................................................................................ 4-6
Core Collection Interfaces ...................................................................................................................... 4-7
Basic Implementations ......................................................................................................................... 4-14
Iterators ................................................................................................................................................... 4-19
Anonymous Implementations ............................................................................................................ 4-22
Synchronized Wrappers ....................................................................................................................... 4-25
Comparing Collections ......................................................................................................................... 4-27
Compatibility ......................................................................................................................................... 4-30
Module Summary ................................................................................................................................. 4-32
Topics .......................................................................................................................................9-1
Topics ........................................................................................................................................................ 9-2
Introducing JDBC .................................................................................................................................... 9-3
JavaSpaces ................................................................................................................................................ 9-4
Goals of JavaSpaces ................................................................................................................................ 9-5
JavaSpaces Concepts ............................................................................................................................... 9-9
Jini ............................................................................................................................................................ 9-12
The Jini Vision ....................................................................................................................................... 9-13
Jini Infrastructure .................................................................................................................................. 9-15
Distributed Jini ...................................................................................................................................... 9-17
HotSpot VM ........................................................................................................................................... 9-19
HotSpot Benefits .................................................................................................................................... 9-20
JavaBlend ................................................................................................................................................ 9-22
Benefits of Java Blend ........................................................................................................................... 9-23
Using Java Blend ................................................................................................................................... 9-24
Module Summary ................................................................................................................................. 9-28