Transcript Java

Java
Java Design Principles
Safety
 Primitive data types have fixed sizes and meanings
 Type safety (strongly typed)
 Strict control of pointers
Object Oriented Language
 Everything is an object
 Common base class
Simplicity
Java
Java features
 Automatic garbage collection
 Nice exception handling
 Object hierarchy
 Polymorphic data structures
 Wrapper classes
 Memory management
 Cloning
Java API Packages
package java.applet
package java.awt
package java.awt.datatransfer
java.awt.event
package
package java.awt.image
package java.beans
package java.io
package java.lang
package java.lang.reflect
package java.math
package java.net
package java.security
package java.security.acl
java.security.interfaces
package
package java.sql
package java.text
package java.util
package java.util.zip
Java
- Sequential Execution (Example 1)
/**
* The HelloWorldApp class implements an application that
* simply displays "Hello World!" to the standard output.
*/
class HelloWorldApp {
public static void main(String[] args) {
System.out.println("Hello World!"); //Display the string.
}
}
Java
- Sequential Execution (Example 2)
public static void main( String[ ] args ){ // Web page grep
if (args.length != 2){ // Input arguments: URL, text
System.out.println("Find String URL");
return;
}
String str = args[0];
try {
URL url = new URL(args[1]); // Open connection, and use page
InputStream in = url.openStream(); // as a stream
StreamTokenizer tokens = new StreamTokenizer(in);
int matchCount = 0; // Count the tokens which match the
while(tokens.nextToken() != StreamTokenizer.TT_EOF) { // input stream
if (tokens.ttype == StreamTokenizer.TT_WORD)
if (str.equalsIgnoreCase(tokens.sval)) // Ignore case in looking
matchCount++; // for matches
}
System.out.println(matchCount + " matches of " + str + " found at " + args[1]);
} catch( MalformedURLException mue) { // Errors if URL is bad, or
System.out.println("Bad URL"); // problems with input
} catch(IOException ioe) {
System.out.println("IO Error");
}
}
Locks and Synchronization (1)
 A variable is any location within a Java program that
may be stored into
 Variables are kept in a main memory that is shared by
all threads
 Every thread has a working memory in which it keeps
its own working copy of variables that it must use or
assign
 The main memory contains the master copy
Locks and Synchronization (2)
Java providing mechanisms for synchronizing
the concurrent activity of threads
Java uses monitors, which are a high-level
mechanism for allowing only one thread at a
time to execute a region of code protected by
the monitor
The behavior of monitors is explained in terms
of locks
Locks and Synchronization (3)
A lock associated with every object
Threads may compete to acquire a lock
No separate lock and unlock actions; instead,
they are implicitly performed by high-level
constructs
Java VM does provide separate monitorenter
and monitorexit instructions
Synchronized statement
 Acquires a mutual-exclusion lock on behalf of the
executing thread
 First computes a reference to an object
 Then it attempts to perform a lock action on that object
and does not proceed further until the lock action has
successfully completed
 After the lock action has been performed, the body of
the synchronized statement is executed
 If execution of the body is ever completed, either
normally or abruptly, an unlock action is automatically
performed
Synchronized method (1)
 Again, first computes a reference to an object
 Automatically attempt to perform a lock action
 Body of method is not executed until the lock action has
successfully completed
 If the method is an instance method, it locks the lock associated
with the instance
 If the method is static, it locks the lock associated with the class
object that represents the class
 If execution of the body is ever completed, either normally or
abruptly, an unlock action is automatically performed
Synchronized method
(2)
A Simple Example:
class Test {
int count;
synchronized void bump() { count++; }
static int classCount;
static synchronized void classBump() {
classCount++;
}
}
Synchronized method
(3)
 The methods wait, notify, notifyAll of class
 object support an efficient transfer of control from one thread to
another. Instead of “spinning”, a thread can suspend itself using
wait until such time as another thread awakens it using notify
 Especially appropriate in situations where threads have a producerconsumer relationship (actively cooperating on a common goal)
rather than a mutual exclusion relationship (trying to avoid conflicts
while sharing a common resource)
 If two or more concurrent threads act on a shared variable, there is
a possibility that the actions on the variable will produce timingdependent results - “race condition”
Class java.lang.Object
Class Object is the root of the class hierarchy. Every class has
Object as a superclass. All objects, including arrays, implement the
methods of this class.
wait(); wait(long); wait(long, int);
Causes the current thread to wait until either some other thread
invokes the notify method or the notifyAll method for this object (or
some other thread interrupts the current thread, or a certain amount
of real time has elapsed)
notify() - Wakes up a single thread that is waiting on this object's
monitor.
notifyAll() Wakes up all threads that are waiting on this object's
monitor.
Class java.lang.Thread
 Extends java.lang.Object
 Methods
 currentThread() Returns a reference to the currently executing thread
object
 getName() Returns this thread's name
 setName(String) Changes the name of this thread to be equal to the
argument name
 getPriority() Returns this thread's priority
 setPriority(int) Changes the priority of this thread.
 run() If this thread was constructed using a separate Runnable run object,
then that Runnable object's run method is called; otherwise, this method
does nothing and returns
 destroy() Destroys this thread, without any cleanup
Class java.lang.Thread (cont’d)









interrupt() Interrupts this thread
interrupted() Tests if the current thread has been interrupted
resume() Resumes a suspended thread
sleep(long) Causes the currently executing thread to sleep (temporarily
cease execution) for the specified number of milliseconds.
start() Causes this thread to begin execution; the Java Virtual Machine
calls the run method of this thread.
stop() Forces the thread to stop executing.
stop(Throwable) Forces the thread to stop executing.
suspend() Suspends this thread.
yield() Causes the currently executing thread object to temporarily pause
and allow other threads to execute.
Creating a New Thread (1)
 Method One: Declare a class to be a subclass of Thread. This subclass
should override the run method of class Thread. An instance of the
subclass can then be allocated and started
 Example:
class PrimeThread extends Thread {
long minPrime;
PrimeThread(long minPrime) {
this.minPrime = minPrime;
}
public void run() {
// compute primes larger than minPrime
...
}
}
//Create a thread and start it running:
PrimeThread p = new PrimeThread(143);
p.start();
Creating a New Thread (2)
 Method Two: Declare a class that implements the Runnable interface.
That class then implements the run method. An instance of the class can
then be allocated, passed as an argument when creating Thread, and
started
 Example:
class PrimeRun implements Runnable {
long minPrime;
PrimeRun(long minPrime) {
this.minPrime = minPrime;
}
public void run() {
// compute primes larger than minPrime
...
}
}
//Create a thread and start it running:
PrimeRun p = new PrimeRun(143);
new Thread(p).start();