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 java options Use –D to specify properties Some 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 Security manager -Djava.security.manager installs the default security manager (very restrictive) -Djava.security.policy specifies the policy file Use policytool utility to generate policy files jar Use jar utility to create jar files Command format like tar File format like zip, but includes a manifest file MANIFEST.MF Jar files can be made executable by adding a Main-Class line to the manifest javadoc javadoc utility generates an HTML documentation, API, with all the classes’ information Uses 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 shouldn’t be used (class, method, or variable) javadoc example package 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 threads Use the built-in Thread class in Java. You need to supply the programming that the thread will follow in order to do multithreaded 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. extend (subclass) the built-in Thread class In 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 name a.start(); } } implement Runnable interface In 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 class Thread aThread = new Thread(aObject, “mud, too”); // Thread name aThread.start(); }} 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 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 Starting threads Invoking its start method causes an instance of class Thread to initiate its run method A Thread terminates when its run method completes by either returning normally or throwing an unchecked exception Threads are not restartable, even after they terminate isAlive returns true if a thread has been started by has not terminated More Thread methods Thread.currentThread returns a reference to the current Thread Thread.sleep(long msecs) causes the current thread to suspend for at least msecs milliseconds Thread.interrupt is the preferred method for stopping a thread (not Thread.stop) Priorities Each 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 it The initial thread associated with a main by default has priority Thread.NORM_PRIORITY (5) getPriority gets current Thread priority, setPriority sets priority A scheduler is generally biased to prefer running threads with higher priorities (depends on JVM implementation) 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. 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 synchronization t.wait() blocks until t.notify() or t.notifyAll() method is called 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. Thread/process states start yield stop 0 sleep/suspend resume 1 2 run stop/end 3 suspend dispatch stop stop 1 – terminated 3 – suspended 2 – running 4 - runnable 4 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. More thread states Blocked – 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 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. 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. 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. 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 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 } }