Welcome to the 3rd Meeting of Java Discovering It's Powers

cavalcadejewelSoftware and s/w Development

Nov 18, 2013 (3 years and 4 months ago)

62 views

Welcome to the 9th Meeting of

Java Discovering It’s Powers

6:30pm to 9:30pm

SF Downtown Center,

UC Berkeley Extension

Tonight’s Agenda List


Review of previous class and taught
materials


Threading


RMI


JDBC

What did we take away from our last meeting?


Event handling in Swing


Event Objects


Windows, and Panels (Layouts)


Listeners (Handlers)

CPU will context switch to
another program


When ? 3 Ways

1.
You are on a single CPU and the time slice
alloted to your program is finished.

2.
Higher priority program such as Operating
System routine needs to serve an interrupt
cause by an exception

3.
The last is when the program has to wait for
an I/O operation and voluntary gives context
to another program. Note, time slot is not
fully used.


Why Threads


The first and second case, there is nothing to do
for program to keep the CPU's attention.


In the third case, where the program waits on I/O,
this is where Threads are used to keep CPU
running the program and not context switch. We
want to fully use the time that has been reserved
for us and not give it up to another program.


When program waits, a thread could crunch some
calculations, or listen for events.

Common Uses for Threads


Double buffering of data. One thread is doing I/O
of the next set of data, while the current thread is
processing that information in memory.


Double buffering for animations, one thread is
generate the next image in memory, while another
is actually repainting the screen.


Timers that wake up other threads at a specific
interval.


Server that handle simultaneous connection
handles each client on a different thread.


Servlet use different threads for different services
offered.

Another way to think of Threads
as a programmer.


Threads = Virtual CPUs

As a programmer, you don't need to know how
the computer implements it, just that modern
computers allow you to perform more than one
job at a time.

Creating Threads


Two ways


Implement the Runnable interface


Or write a class that extends Thread as super
class and override the run() method.


Example implementing Runnable
interface

Public class TestThread {



public static void main (String args[]) {




Xyz r = new Xyz();




Thread t = new Thread ( r );




t.start(); // Note Threads do not start themselves.



}

}

Class Xyz implements Runnable {



int j=0;



public void run () {




while (true) {





System.out.println ("Hello " + j++);





if (j == 50) { break;}




}



}

}


Threads sharing the same data


Multithreaded programming allows us to
create multiple thread instance from the
same runnable instance


Thus



Thread t1 = new Thread ( r ); //notice, they all have the r as the runnable



Thread t2 = new Thread ( r ); // instance which means all the threads



Thread t3 = new Thread ( r ); // share the same data




t1.start(); //start the first thread



t2.start(); //start the second thread



t2.start(); //start the third thread

Starting a Thread


Using the start() method


Placing the thread into a runnable state

Example of extending Thread

Public MyThread extend Thread {


public void run () {



while (true) {




//do calculations




//and interesting stuff here



}


}




public static void main( String [] args) {



Thread t = new MyThread();



t.start();

//Put the thread into the runnable state.


}

}



Which is better to use ?


Implementing Runnable


Better object oriented design


Single Inheritance


Extending a Thread


Much simpler programming. Many programmers
choose this. Limited in terms of single inheritance.


And you will by able to call wait() or join() verse in a
Runnable class, you might have to use the


Thread.currentThread().join()


Thread States Diagram

New Thread state


Thread myThread = new MyThreadClass();



Leaves a thread in New Thread state.


Only have option of start() or stop() to move it
into the Runnable state or the dead state. Stop()
has been deprecated since JDK1.3; it causes
heap/stack corruption and does not complete
release resource, and memory leaks.


IllegalThreadStateException

will be thrown if you
try to do something weird like make it sleep when
it has not started yet.

Runnable State



Thread myThread = new MyThreadClass();



myThread.start();


Start() puts the thread in an executable state called
the Runnable state.


Calls the Thread's run() method


Called a Runnable State because the Java Runtime
system schedules all the runnable threads based on
priority , thus a Runnable thread may not be running
all the time, and thus the name runnable.

Not Runnable State


Several events can put a thread in this state.


Someone invokes sleep on the thread


Someone interrupts the thread.


Thread uses join() and waits for another thread to finish


Thread uses it wait() and waits on a conditional variable


Thread has blocked on I/O.


Waiting for a synchronized (), thus blocks in a lock
pool of threads waiting for a lock to be available.

Dead State


Natural death, when it finishes the run()
method and it goes to the death state
naturally.


Thread.destroy() can move it to the death
state without clean up.


Best to build in a self destruct method in the
Runnable Class or the Thread Class. There
are thread that zombie out and never die.
They hold resources and can crash your
system if you have enough hangin Threads.

Example of Self Destruct Routine

Class myRunnable implements Runnable {


boolean timeToQuit = false;


void run () {



while ( ! timeToQuite ) {




//execute something interesting



}


}




void stopRunning () {



timeToQuit = true; // booleans are atomic by nature


}

}

Basic Thread control


isAlive()
, returns true if the thread has be started but not
yet died



join()
, suspend the current thread and wait until the thread
to join is finished.


I.e. timerThead.join() will suspend the current thread until
timerThread has finish executing



sleep(1000)

is another way to halt execution. Must catch
InterruptedException as the thread may be woken by
interrupt(). May not wake exactly after 1000 millisec due
to other Thread which may be higher priority and preempts
this the Thread.

Synchronized Key word


Every object has a flag which can be though of as
a "lock flag".


Synchronized allows interaction with the lock flag


public void push(char c) {



synchronize (this) {




data[idx] = c;




idx ++;



}


}

Atomicity


Synchronize helps to keep a set of critical
operations atomic, like one un separated
operation. This will not allow corruption of
data.


Let’s have a look at the Color Example by
Bill Venners, on Design for Thread Safety

The infamous Critcal Section


What is a critical section ?


A snippet of code which corrupt data when
there is multithreading involve.


An area of your code which both there could be
read and writing of data that can have
information at an un know state.


Need to synchronize this critical section

Wait and Notify


waitingThread.wait(long timeout)


taxiThread wait until there is a


taxiThread.notify() issue some where



Both wait() and notify method have to be issue
in sychronized methods because they require.
This sychronized(taxi) block needs to surround
the wait or notify calls


Solves the supply/consumer dilemma.


Singleton, Mutex, and Spinlocks.


Singleton is a pattern in which there is one and only one
unique resource. Implemented with a static variable in a
class which is multithreaded.


Mutex, mutually exclusive. Bathrooms on a airplane. Give
the lock on the single resource, only one passenger can get
into the bathroom on the airplane at one time.


Spinlocks are basically wait() call inside of while
statement. The while is based on some conditional variable
share by other threads. Spinlocks are useful in many
instance where multiple threads are waiting for one
resource.

What is a deadlock ?


Two threads waiting for a lock from the
each other


It is not detected or avoided, hard to find
and debug


It can be avoided by

* Making sure that not multiple threads are
dependent on each other’s locked resource in
order to move to an unblocked stated.

RMI


Remote Method Invocation


A way to do RPC (Remote Procedure Call)
in Java.


Different than CORBA.


RMI does not use Object Request Brokerage.


CORBA is language neutral, RMI uses Java
only.

Process involved in RMI

1.
A client invokes a method of a remote object

2.
Server runs in the background and own the
instance of this object

3.
Object Registry runs to find names space and
object. Remote object are listed much like in a
telephone book. Much like LDAP, a directory of
name spaces and names.

// rmiregistry &


Packages need


java.rmi.*;


java.rmi.server.*;


Reflection ?


Part of the java.lang.reflect package


API use with Java Beans to determine at run
time the properties of a class.


Also used by serialization at a lower level
way to get the characteristics of a class to
determine to transport it over a stream or to
storage it as a persistent object.

Parts of the Object class


The method getClass() of the class Object will
return a Class class.

String myString = "Foo";

Class stringc = myString.getClass();


You can also use the static method
Class.forName("FlashCards"); of a the Class class
to find a class.


As well as using the newInstance() to create a
brand new instance of this class that you found.

Three features for accessing a
class


The three features are embodied in


java.lang.reflect.Method


java.lang.reflect.Constructor


java.lang.reflect.Field


There are methods in the Class class for returning
one of the three class mention above


Field [] getFields();

//Private field are not r/w


Method [] getMethods();


Constructors[] getConstructors();

Example of Reflection


Method [] methods = myUnknownObject.getClass().getMethods();


//could do the same for getFields or getConstructors.


for (int I=0; I< methods.length;I++) {



Systems.out.println( methods[I]);


}



Javap is an executable provide by the java
sdk to print out the public methods of a
class. // Let me demonstrate.



OMG


Stands for Object Management Group, a
consortium of companies to create a
standard to brokerage of object. Microsoft is
not one them.


Microsoft's CORBA equavilent is DCOM
and COM. Anyone using .NET ?


CORBA


C
ommon
O
bject
R
equest
B
roker
A
rchitecture


Similar to RMI, but more general and
provides more services.


Use an language (IDL) indepent to define
RPC.


module HelloApp {



interface Hello {




string sayHello();



};



};

CORBA Overview

IDL grinding


Java files stubs and skeletons are generated
by an executable called idl2java.exe


This executable creates files which contain
stub as well as skeleton for the


Advantages to CORBA


Multiple agents running on multiple
machine to create redundancy and
brokerage of objects.


Can write intelligent agents to load balance
and route traffic according to load.


Scalable. Add more servers to handle large
loads and traffic.


For more info, go to
http://www.corba.org

JDBC


JDBC is Java Database Connectivity, kind
of like Microsoft's ODBC


JDBC allow programs to interact with
various Database packages such as mySQL,
Oracle, MS SQL Server and my more.


Must have a specific JDBC driver written for
each vendor specific database


Check the following website for a complete list

http://servlet.java.sun.com/products/jdbc/drivers


Package java.sql


DriverManager



class that manages drivers for
connecting to specific RDBMS’s.


Connection



interface that describes the methods that
must be available to manage a connection to an RDBMS.


Statement



interface that describes the methods that
must be available to send a statement to the RDBMS for
execution. Statements can be any legal SQL statements,
including RDBMS
-
specific statements, as the syntax is
checked by the specific RDBMS you are connected to.


ResultSet


interface that describes the methods that must
be available to manage the results of a SELECT query.


JDBC abstraction



Oracle



MySQL



MS Access




Flat

Files



Java Application



Connection


Statement


create, insert, update, query


ResultSet


results of a query


DBMS
-
Specific Driver:
mm
driver for MySQL


Steps in using a database


Setup your database.


Download the driver and follow
instruction on installing it, add it to the
classpath as well.

1.
Load the driver in your program

Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");

2.
Connect to the database

Connection con = DriverManager.getConnection(url,
"myLogin", "myPassword"); //remember to close after
using

//url is basically the data source name, read the documentation

//by the driver so figure what the url should me.

Last steps in using the database

1.
Create a Statement

Statement stmt = con.createStatement();

//need to close (.close()
)

2.

Do an Update


stmt.executeUpdate(createTableCoffees);


//create a Table in the database

3.

Do an Select, or Query


String query = "SELECT COF_NAME, PRICE FROM COFFEES";
ResultSet rs = stmt.executeQuery(query);



while (rs.next()) {



String s = rs.getString("COF_NAME");



float n = rs.getFloat("PRICE");




System.out.println(s + " " + n);



}