Java 3: Odds & Ends Advanced Programming Techniques.

Slides:



Advertisements
Similar presentations
Introduction to Java 2 Programming Lecture 3 Writing Java Applications, Java Development Tools.
Advertisements

Concurrent Programming Abstraction & Java Threads
Ade Azurat, Advanced Programming 2004 (Based on LYS Stefanus’s slides) Advanced Programming 2004, Based on LYS Stefanus’s slides Slide 2.1 Multithreading.
Multi-threaded applications SE SE-2811 Dr. Mark L. Hornick 2 What SE1011 students are told… When the main() method is called, the instructions.
Algorithm Programming Concurrent Programming in Java Bar-Ilan University תשס"ח Moshe Fresko.
George Blank University Lecturer. CS 602 Java and the Web Object Oriented Software Development Using Java Chapter 4.
Thread Control methods The thread class contains the methods for controlling threads Thread() create default thread Thread(target: runnable ) creates new.
Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All rights reserved L19 (Chapter 24) Multithreading.
CS220 Software Development Lecture: Multi-threading A. O’Riordan, 2009.
1 Threads (Part I) Introduction to Threads and Concurrency Overview  Introduction to Threads of Computation  Creating Threads in java an Example  Thread.
Threads A thread is a program unit that is executed independently of other parts of the program A thread is a program unit that is executed independently.
Definitions Process – An executing program
Multithreading in Java Nelson Padua-Perez Chau-Wen Tseng Department of Computer Science University of Maryland, College Park.
Threads Just Java: C10–pages 251- C11–pages 275-
Multithreading.
Parallel Processing (CS526) Spring 2012(Week 8).  Thread Status.  Synchronization in Shared Memory Programming(Java threads ) ◦ Locks ◦ Barriars.
Java Programming: Advanced Topics
1 Java Threads Instructor: Mainak Chaudhuri
Threads. Overview Problem Multiple tasks for computer Draw & display images on screen Check keyboard & mouse input Send & receive data on network Read.
Lecture 5 : JAVA Thread Programming Courtesy : MIT Prof. Amarasinghe and Dr. Rabbah’s course note.
Quick overview of threads in Java Babak Esfandiari (extracted from Qusay Mahmoud’s slides)
Today’s Agenda  Quick Review  Finish Java Threads  The CS Problem Advanced Topics in Software Engineering 1.
Dr. R R DOCSIT, Dr BAMU. Basic Java : Multi Threading 2 Objectives of This Session State what is Multithreading. Describe the life cycle of Thread.
111 © 2002, Cisco Systems, Inc. All rights reserved.
Java Threads. What is a Thread? A thread can be loosely defined as a separate stream of execution that takes place simultaneously with and independently.
Threads in Java. Processes and Threads Processes –A process has a self-contained execution environment. –Has complete set of runtime resources including.
CSC 205 – Java Programming II Applet. Types of Java Programs Applets Applications Console applications Graphics applications Applications are stand-alone.
Threads.
Javadoc A very short tutorial. What is it A program that automatically generates documentation of your Java classes in a standard format For each X.java.
Multithreading in Java Sameer Singh Chauhan Lecturer, I. T. Dept., SVIT, Vasad.
Introduction to Threads Session 01 Java Simplified / Session 14 / 2 of 28 Objectives Define a thread Define multithreading List benefits of multithreading.
Advanced Programming 2004, based on LY Stefanus’s slides slide 8.1 Multithreading : Thread Scheduling ThreadGroup.
In Java processes are called threads. Additional threads are associated with objects. An application is associated with an initial thread via a static.
Multithreading in JAVA
Object-oriented Programming in Java. © Aptech Ltd. Introduction to Threads/Session 7 2  Introduction to Threads  Creating Threads  Thread States 
Java Thread and Memory Model
Threads Doing Several Things at Once. Threads n What are Threads? n Two Ways to Obtain a New Thread n The Lifecycle of a Thread n Four Kinds of Thread.
15.1 Threads and Multi- threading Understanding threads and multi-threading In general, modern computers perform one task at a time It is often.
Concurrency Control 1 Fall 2014 CS7020: Game Design and Development.
Multi-Threading in Java
Multithreaded programming  Java provides built-in support for multithreaded programming. A multithreaded program contains two or more parts that can run.
Threads in Java Threads Introduction: After completing this chapter, you will be able to code your own thread, control them efficiently without.
Thread A thread represents an independent module of an application that can be concurrently execution With other modules of the application. MULTITHREADING.
Multithreading. Multitasking The multitasking is the ability of single processor to perform more than one operation at the same time Once systems allowed.
SourceAnatomy1 Java Source Anatomy Barb Ericson Georgia Institute of Technology July 2008.
Threads b A thread is a flow of control in a program. b The Java Virtual Machine allows an application to have multiple threads of execution running concurrently.
Chapter 13: Multithreading The Thread class The Thread class The Runnable Interface The Runnable Interface Thread States Thread States Thread Priority.
1 Threads in Java Jingdi Wang. 2 Introduction A thread is a single sequence of execution within a program Multithreading involves multiple threads of.
Concurrency in Java MD. ANISUR RAHMAN. slide 2 Concurrency  Multiprogramming  Single processor runs several programs at the same time  Each program.
Today Threading, Cont. Multi-core processing. Java Never Ends! Winter 2016CMPE212 - Prof. McLeod1.
Java Thread Programming
Threads in Java Jaanus Pöial, PhD Tallinn, Estonia.
Modern Programming Tools And Techniques-I
Multithreading / Concurrency
Multithreading Lec 23.
Multi Threading.
Java Multithreading.
Multithreaded Programming in Java
Threads Chate Patanothai.
Definitions Concurrent program – Program that executes multiple instructions at the same time. Process – An executing program (the running JVM for Java.
Multithreading.
Java Based Techhnology
Multithreading.
Multithreaded Programming
Multithreading in java.
Threads and Multithreading
9. Threads SE2811 Software Component Design
Lecture 19 Threads CSE /6/2019.
9. Threads SE2811 Software Component Design
Java Chapter 3 (Estifanos Tilahun Mihret--Tech with Estif)
Presentation transcript:

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 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 – author name (for – parameter name and description – description of return value – exception name and – 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. * Thomas Funck 1.0 * 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. o the object to be viewed 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 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.

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 stop start yield sleep/suspendresume run stop/end stop dispatch suspend 1 – terminated 2 – running 3 – suspended 4 - runnable

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 }