java 3: odds & ends advanced programming techniques

Click here to load reader

Download Java 3: Odds & Ends Advanced Programming Techniques

Post on 20-Jan-2016




0 download

Embed Size (px)


  • Java 3: Odds & EndsAdvanced 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

  • java optionsUse D to specify propertiesSome often used properties:http.proxyHosthttp.proxyPortUse X to specify non-standard properties: -Xms set initial Java heap sizeSee java documentation for more info

  • Security the default security manager (very restrictive) the policy fileUse policytool utility to generate policy files

  • jarUse 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

  • javadocjavadoc 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

  • 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 shouldnt be used (class, method, or variable)

  • 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 { }

  • Java threadsUse 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 JavaExtend (subclass) the Thread class. Provide a run method in the subclass.Create a Thread object incorporating an object that specifies the Threads run method.

  • extend (subclass) the built-in Thread classIn file class AThread extends Thread {public AThread(String name) {super(name);} public void run() {System.out.println(My name is + getName());}}

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

  • implement Runnable interfaceIn file class AClass implements Runnable {public void run() {System.out.println(My name is + Thread.currentThread().getName());}}

    In file 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();}}

  • Extend (inherit) Thread versus implement RunnableThe implementing Runnable technique allows you to extend another class as well as getting threads.Since Java does not have full multiple inheritance, you cant do that with the first method.Thread itself implements Runnable

  • Thread ConstructionDifferent Thread constructors accept combinations of arguments supplying:A Runnable object, in which case Thread.start invokes run of the supplied Runnable objectA String that serves as an identifier. Not useful except for tracing and debuggingThreadGroup in which the new Thread should be placed

  • Starting threadsInvoking 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

  • More Thread methodsThread.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)

  • 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)

  • The run queue of runnable threadsThe 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.

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

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

  • Thread States and SchedulingA 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.

  • Thread/process states1 terminated2 running3 suspended4 - runnable

  • Thread statesNew 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.

  • More thread statesBlocked the thread is waiting for something to happen It is waiting for an i/o operation it is executing to complete It has been told to sleep for a specified period of time through the sleep method It 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.

  • More thread statesDeadThe 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.

  • Javas synchronized featureEach Java object has a lock associated with it. A method can be declared as synchronizedpublic 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.

  • Static methods versus ordinary methodsFor 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.

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

  • An example of synchronization on objectspublic static void SortIntArray( int[] a) {synchronize(a) {// do array sort here gets a lock on the array a so some other thread cant change the values// in a while were trying to do the sorting}}