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

cavalcadejewelSoftware and s/w Development

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


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




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

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

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

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

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

Servlet use different threads for different services

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

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


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();


//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 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.


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();


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

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

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

, 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


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 ++;




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

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

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.


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

Process involved in RMI

A client invokes a method of a remote object

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

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



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

The three features are embodied in




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.


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 ?



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

Use an language (IDL) indepent to define

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


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


Package java.sql


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


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


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.


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

JDBC abstraction



MS Access



Java Application



create, insert, update, query


results of a query

Specific Driver:
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.

Load the driver in your program


Connect to the database

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

//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

Create a Statement

Statement stmt = con.createStatement();

//need to close (.close()


Do an Update


//create a Table in the database


Do an Select, or Query

ResultSet rs = stmt.executeQuery(query);

while (rs.next()) {

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

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

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