java 3: odds & ends advanced programming techniques

28
Java 3: Odds & Ends Advanced Programming Techniques

Upload: brianna-atkinson

Post on 20-Jan-2016

229 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: Java 3: Odds & Ends Advanced Programming Techniques

Java 3: Odds & Ends

Advanced Programming Techniques

Page 2: Java 3: Odds & Ends Advanced Programming Techniques

javac options

-deprecation to get deprecation information-d to specify the destination for class files-verbose for more detailed output-O for optimization

Page 3: Java 3: Odds & Ends Advanced Programming Techniques

java options

Use –D to specify propertiesSome often used properties: http.proxyHost http.proxyPort

Use –X to specify non-standard properties: -Xms<size> set initial Java heap size

See java documentation for more info

Page 4: Java 3: Odds & Ends Advanced Programming Techniques

Security manager

-Djava.security.managerinstalls the default security manager

(very restrictive)-Djava.security.policy

specifies the policy fileUse policytool utility to generate policy files

Page 5: Java 3: Odds & Ends Advanced Programming Techniques

jar

Use jar utility to create jar filesCommand format like tarFile format like zip, but includes a manifest file MANIFEST.MFJar files can be made executable by adding a Main-Class line to the manifest

Page 6: Java 3: Odds & Ends Advanced Programming Techniques

javadoc

javadoc utility generates an HTML documentation, API, with all the classes’ informationUses the code and the special javadoc comments/** starts the special doc comment*/ ends it

Page 7: Java 3: Odds & Ends Advanced Programming Techniques

javadoc continued

@author – author name (for class)@param – parameter name and description (method)@return – description of return value (method)@exception – exception name and description@deprecated – an item is obsolete and shouldn’t be used (class, method, or variable)

Page 8: Java 3: Odds & Ends Advanced Programming Techniques

javadoc examplepackage stars.ui; import java.awt.*; /** * A Viewer for text. * * @author Thomas Funck * @version 1.0 * * @see Viewer */ public class TextViewer extends Frame implements Viewer {

/** The TextArea used to display text */ private TextArea text; /** Creates a new TextViewer */ public TextViewer() {... } /** Sets the object to be viewed. * @param o the object to be viewed * @exception ClassCastException thrown when the specified object * is not of type String */ public void setObject(Object o) throws ClassCastException { … }

Page 9: Java 3: Odds & Ends Advanced Programming Techniques

Java threads Use the built-in Thread class in Java. You need to supply the programming

that the thread will follow in order to do multi-threaded programming.

There are two ways to get a new thread in Java Extend (subclass) the Thread class.

Provide a run method in the subclass. Create a Thread object incorporating an

object that specifies the Thread’s run method.

Page 10: Java 3: Odds & Ends Advanced Programming Techniques

extend (subclass) the built-in Thread classIn file AThread.java:

class AThread extends Thread {public AThread(String name) {super(name);}

public void run() {System.out.println(“My name is” + getName());}

}

In file test.java:class test {

public static void main(String[] args) {AThread a = new AThread(“mud”); // Thread namea.start();}

}

Page 11: Java 3: Odds & Ends Advanced Programming Techniques

implement Runnable interfaceIn file AClass.java:

class AClass implements Runnable {public void run() {System.out.println(“My name is “ +

Thread.currentThread().getName());}}

In file test2.java:

class test {public static void main(String[] args){AClass aObject = new AClass();

// Use alternative constructor for Thread classThread aThread = new Thread(aObject, “mud, too”);

// Thread nameaThread.start();

}}

Page 12: Java 3: Odds & Ends Advanced Programming Techniques

Extend (inherit) Thread versus implement Runnable

The “implementing Runnable” technique allows you to extend another class as well as getting threads.Since Java does not have full multiple inheritance, you can’t do that with the first method.Thread itself implements Runnable

Page 13: Java 3: Odds & Ends Advanced Programming Techniques

Thread Construction

Different Thread constructors accept combinations of arguments supplying: A Runnable object, in which case Thread.start invokes run of the supplied Runnable object

A String that serves as an identifier. Not useful except for tracing and debugging

ThreadGroup in which the new Thread should be placed

Page 14: Java 3: Odds & Ends Advanced Programming Techniques

Starting threads

Invoking its start method causes an instance of class Thread to initiate its run methodA Thread terminates when its run method completes by either returning normally or throwing an unchecked exceptionThreads are not restartable, even after they terminateisAlive returns true if a thread has been started by has not terminated

Page 15: Java 3: Odds & Ends Advanced Programming Techniques

More Thread methods

Thread.currentThread returns a reference to the current ThreadThread.sleep(long msecs) causes the current thread to suspend for at least msecs millisecondsThread.interrupt is the preferred method for stopping a thread (not Thread.stop)

Page 16: Java 3: Odds & Ends Advanced Programming Techniques

PrioritiesEach Thread has a priority, between Thread.MIN_PRIORITY and Thread.MAX_PRIORITY (from 1 to 10)Each new thread has the same priority as the thread that created itThe initial thread associated with a main by default has priority Thread.NORM_PRIORITY (5)getPriority gets current Thread priority, setPriority sets priorityA scheduler is generally biased to prefer running threads with higher priorities (depends on JVM implementation)

Page 17: Java 3: Odds & Ends Advanced Programming Techniques

The “run queue” of runnable threads

The Java language specification does not specify how Java is supposed to choose the thread to run if there are several runnable threads of equal priority.One possibility – pick a thread and run it until it completes, or until it executes a method that causes it to move into a non-running state.Another possibility – “time slicing”: pick a thread and run it for a short period of time. Then, if it is not finished, suspend it and pick another thread to run for the same period of time.

Page 18: Java 3: Odds & Ends Advanced Programming Techniques

The semantics of yield()public static void yield() Causes the currently executing thread object to

temporarily pause and allow other threads to execute.

Java Language Reference:“In some cases, a large number of threads could be

waiting on the currently running thread to finish executing before they can start executing. To make the thread scheduler switch from the current running thread to allow others to execute, call the yield() method on the current thread. In order for yield() to work, there must be at least one thread with an equal or higher priority than the current thread..”

Page 19: Java 3: Odds & Ends Advanced Programming Techniques

Thread synchronization

t.wait() blocks until t.notify() or t.notifyAll() method is called

Page 20: Java 3: Odds & Ends Advanced Programming Techniques

Thread States and Scheduling

A Java thread can be in new, runnable, running, suspended, blocked, suspended-blocked and dead.The Threads class has methods that move the thread from one state to another.

Page 21: Java 3: Odds & Ends Advanced Programming Techniques

Thread/process states

0 1 2 3 4

stop

start yield

sleep/suspend resume

runstop/end

stop

stop

dispatch

suspend

1 – terminated

2 – running

3 – suspended

4 - runnable

Page 22: Java 3: Odds & Ends Advanced Programming Techniques

Thread states

New state – a Thread newly created.Runnable – after being started, the Thread can be run. It is put into the “run queue” of Threads and waits its turn to run. “Runnable” does not mean “running”.Running – the thread is executing its code. On a uniprocessor machine, at most one thread can run at a time.

Page 23: Java 3: Odds & Ends Advanced Programming Techniques

More thread states

Blocked – the thread is waiting for something to happenIt is waiting for an i/o operation it is executing to completeIt has been told to sleep for a specified period of time through the sleep methodIt has executed the wait() method and will block until another thread executes a notify() or notifyAll() method.It will return to runnable state after sleeping, notifying, etc.

Page 24: Java 3: Odds & Ends Advanced Programming Techniques

More thread states

Dead The final state. After reaching this

state the Thread can no longer execute.

A thread can reach this state after the run method is finished, or by something executing its stop() method.

Threads can kill themselves, or a thread can kill another thread.

Page 25: Java 3: Odds & Ends Advanced Programming Techniques

Java’s synchronized feature

Each Java object has a lock associated with it. A method can be declared as synchronized

public synchronized void methodA(…) {…}

Only one thread can run a synchronized method of an object at a time. The lock is set when a thread starts execution of the synchronized method. A thread blocks if the lock is currently held by some other thread running a synchronized method of the object.

Page 26: Java 3: Odds & Ends Advanced Programming Techniques

Static methods versus ordinary methods

For synchronized static methods, Java obtains a lock for the class before executing the method.For synchronized non-static methods, Java obtains a lock for the object before executing the method.

Page 27: Java 3: Odds & Ends Advanced Programming Techniques

Java can synchronize on an object, too.

synchronized (expression) statement; “expression” is something that must

resolve to an object or an array. There will be an internal lock associated with that object or array, and the thread must obtain a lock on it before it will execute the statement, which is regarded as a critical section of code.

Page 28: Java 3: Odds & Ends Advanced Programming Techniques

An example of synchronization on objects

public static void SortIntArray( int[] a) {synchronize(a) {// do array sort here… gets a lock on the

array a so some other thread can’t change the values

// in a while we’re trying to do the sorting

}}