cs1520a - Course Notes for CS 1520 Programming Languages...

Info iconThis preview shows page 1. Sign up to view the full content.

View Full Document Right Arrow Icon
This is the end of the preview. Sign up to access the rest of the document.

Unformatted text preview: Course Notes for CS 1520 Programming Languages for Web Applications By John C. Ramirez Department of Computer Science University of Pittsburgh These notes are intended for use by students in CS1520 at the University of Pittsburgh and no one else These notes are provided free of charge and may not be sold in any shape or form These notes are NOT a substitute for material covered during course lectures. If you miss a lecture, you should definitely obtain both these notes and notes written by a student who attended the lecture. Material from these notes is obtained from various sources, including, but not limited to, the following: 4 Learning Java, multiple editions, by Patrick Niemeyer and Jonathan 4 4 4 4 Knudsen (O'Reilly) Java Software Solutions (multiple editions) by John Lewis and William Loftus (AddisonWesley) Java How to Program, 3rd Edition by Deitel and Deitel (Prentice Hall) Programming the World Wide Web by Robert W. Sebesta (AW) java.sun.com and its many sublinks 2 Goals of Course To examine and use some of the advanced features of Java, especially those pertinent to Web Programming 4 We will look at some things you may not have covered in your CS401/CS445/CS1501 sequence Ex. Multithreading and network communication 4 It is expected that you are already familiar with Java syntax and many of its features Including inheritance, polymorphism, interfaces, general objectoriented design, exception handling and eventdriven programming with graphical components 3 Goals of Course To learn and utilize the PHP language, and its applications 4 PHP syntax, constructs and basic language features 4 Using PHP for serverside embedded scripts Writing and processing HTML forms with PHP 4 Regular expression handling in PHP 4 Using PHP for Web database access With a MySQL database We will cover the basics of using MySQL and DB development as well 4 Goals of Course To learn and utilize the JavaScript 4 Learning the basics of the language language in conjunction with html files 4 Using Javascript in conjunction with DOM to add dynamic content to web pages Ex: Doing clientside processing of forms Checking form input, etc. 4 Using AJAX techniques to make web apps more like standalone applications Updating a web page without requiring a full refresh 5 Goals of Course As time permits... 4 To learn and utilize XML and how it can be used in Web applications 4 To learn the basics of the Perl language Writing stand alone Perl programs Using Perl and its features for Web applications 4 To learn the basics of the C# language How it is similar to and different from Java Using C# with Visual Studio .net to create Web applications 6 You should be already familiar with Java and have used it in CS0401/445/(1501) 4 You are expected to know objectoriented Lecture 1: Getting Started programming (including inheritance and polymorphism), basic graphics and basic event driven programming 4 In this course we concentrate on two advanced features of Java that are useful for internet / web programming: Threads and multithreaded programs Sockets and network programming Allow for pseudoparallel execution Allow for clientserver applications 7 Lecture 1: Getting Started 4 However, if you feel that you need to review some Java basics, I recommend the following: available at http://java.sun.com Read Chapters 16 in Learning Java ASAP The JDK is in the CD in the Learning Java text, and also More information is available at http://java.sun.com, including tutorials, examples and API documentation (in case you'd prefer not to buy another book) I will have some handouts online (with comments) that you can read over see the CS 1520 Web site Also see my CS 0401 notes/handouts from last Fall: http://www.cs.pitt.edu/~ramirez/cs401/handouts/ http://www.cs.pitt.edu/~ramirez/cs401/cs401.ppt Also see some additional review notes and Handouts 1 to 12: http://www.cs.pitt.edu/~ramirez/cs1520/review.ppt Note that these have not been updated for JDK 1.5 (see CS 0401 handouts for some JDK 1.5 features) 8 Lecture 1: Review Example Let's look at one example to quickly review graphics and eventdriven programming 4 ex13.java 4 Program to allow the user to draw and move shapes in the window 4 Note the classes used as well as the programming logic 4 Note also that this can be done in different ways 4 Read the comments thoroughly 9 Lecture 2: Intro. to Threads Background 4 Most programs you have written so far Single flow of execution Logically only a single statement may be executed at any given time 4 Often in real life we need to do more than one thing "at the same time" Talk and chew gum Text message and drive your car Take CS1520 notes and read email and sleep 10 Lecture 2: Intro. to Threads 4 Many programming apps require this also Checking for life on other planets using millions of computers (see: http://setiathome.berkeley.edu/) Using your Unixs account Multiprocessing: using many processors simultaneously for a common purpose Input audio "stream" while playing Multiprogramming / preemptive multitasking: sharing execution between 2 or more independent jobs (each with own data these jobs are also usually called processes) Multithreading: portions of a program (with shared data) may execute concurrently > http://en.wikipedia.org/wiki/Thread_(computer_science) 4 Systems can utilize more than one of above 11 Lecture 2: Intro. to Threads Java Threads 4 Main ideas Objects that can run "at the same time" Chapter 8 in Neimeyer, online in Java Tutorial Code should assume that threads execute in parallel, even if a uniprocessor is used Idea is that we cannot assume (without additional code) that threads will be executed in any specific order, for any specific amount of time A single application or applet may have many threads in it Scheduler manages which threads are running based on various factors 12 Ex. timeslicing, priority, waiting for I/O Lecture 2: Intro. to Threads Shared data must be managed properly to maintain consistency If multiple threads are accessing the same variables, we must take measures to ensure that the values are always what we expect them to be We do this using synchronized methods and data blocks we'll see shortly Different parts of your image may be updated at different times (and at different rates) Threads are a great way to allow these different components to function "independently together" Very useful for GUIs, animation, etc. 13 Lecture 2: Intro. to Threads Java Thread Basics See 4 Thread is a predefined class whose objects have http://java.sun.com/docs/books/tutorial/essential/concurrency/index.html the ability to run() once they are start()ed 4 A thread that is running is simply executing the run() method The run() method can do whatever we want the thread to accomplish It usually contains a loop, and often also has a sleep() component Idea is that the thread will worksleepworksleep until it terminates 14 Lecture 2: Intro. to Threads When this method's execution finishes for a given thread, the thread dies (although the the dead thread object still exists) Usually a condition occurs that causes the loop to terminate In early Java versions, we could also explicitly kill a thread by calling its stop() method, but this method is now DEPRECATED due to its problems in causing data inconsistency See MUCH additional information in the Java 2 API. Look up class java.lang.Thread and go from there > We will see why shortly However, a thread can be interrupted many times due to various factors Ex. timeslice elapses, I/O, sleep, wait() We should handle these situations correctly 15 Lecture 2: Intro. to Threads Thread Syntax 4 new class We can get threads to run in two basic ways 1) Extend the Thread class and override run() for the These threads will be running "on themselves" Each different thread object will have its own "copy" of the run() method, and it will have its own copy of any data used by the run() method (unless it is static data) In this situation the different threads do not really interfere with each other's data However the execution still changes between them and we must handle this See Bounce.java (and also ex14.java) 16 Lecture 2: Intro. to Threads 1) Link a Thread to an object that implements the Runnable interface The Runnable object does NOT itself have to be a Thread These threads will be running on the Runnable object(s) If we do not want the threads to share data we can create a separate thread object to go with each Runnable object > The thread is running, but it is executing the run() method defined in the Runnable object > Can be any Java class that implements Runnable See Bounce2.java > Object can extend a different class and still be Runnable > Object can be run with multiple threads (ex: stop & start) > Can allow more flexibility to programmer 17 Lecture 2: More on Threads Concurrency Concerns 4 Note that more than one thread may run on a single object This means that the same run() method may be executed separately by each of the threads that are running on that object In this case the data in that object is shared amongst the threads Great care must be taken the ensure that the threads access the data so that it is not corrupted, since one Thread may be "in the middle" of something when it is switched out 18 Lecture 2: More on Threads Data concerns when using threads 4 Threads are concurrent (or at least simulated concurrent) Data consistency is a problem when data is shared between threads 1)read(balance); 2)if (balance > withdraw_amount) { 3) pay_out(withdraw_amount); 4) balance -= withdraw_amount; 5) write(balance); } Problem occurs when: Thread 1 executes line 1 Thread 2 executes line 5, dropping balance below withdraw_amount Thread 1 pays out anyway 19 Lecture 3: More on Threads Note that if we could prevent two threads from executing that code segment at the same time, problem would go away Java accomplishes this by using MONITORS Monitors are implemented in Java on objects Data structures that can be accessed by only 1 thread at a time Each object has a LOCK Only 1 thread at a time may obtain the lock only the thread with the lock may access the critical data Once lock is obtained, other threads must wait for it to be released, then they will contend for it The lock makes a block of sensitive code atomic the scenario described before cannot occur 20 Lecture 3: More on Threads Synchronizing Threads 4 Locks are implicitly obtained in Java through use of synchronized methods and blocks 4 Syntax: public synchronized void foo() { } OR synchronized (objectref) // block { } // method 21 Lecture 3: More on Threads 4 An object may have many synchronized methods and/or blocks But only one thread may be executing ANY of them at a time (it obtains the lock) Other threads must wait until lock becomes free See BounceKey.java See BounceKeySynch.java See ex15.java, ex15b.java Once lock is free, other threads contend for it Highest priority chosen, but for equal priority, it is not necessarily a queue 22 Lecture 4: More on Threads 4 Thread with the lock will keep it until it completes the synchronized code, even if it is switched out/does I/O, etc. Sometimes a thread with the lock may voluntarily give it up (before finishing the synchronized method) Some other condition prevents it from continuing For example, Consumer/Producer We call this idea cooperation synchronization > Assume a Producer "produces" data and a Consumer "consumes" it. > To make sure data isn't consumed before it is produced, synchronized methods are used > Threads must be synchronized in order to cooperate with each other 23 Lecture 4: More on Threads But if Consumer and Producer operate at different rates, data may not be available when Consumer tries to consume (or no space may be available for new data from Producer) show on board How to handle this? 1)One way is for the Threads to keep trying the operations until the condition is true (ex: for Consumer, keep checking until data is there) 2)A better way is for the thread to wait until conditions have changed to proceed any further within the synchronized area > However, this is VERY inefficient, since the Threads may spin many times until the condition is true > We could just sleep() in our loop to approximate this, but a better way is to have some signaling mechanism > Don't wake up until there is good reason to 24 Lecture 4: More on Threads In Java this is done with a call to wait() A thread that has called wait() cannot resume execution until 2 things occur: Called by a Thread from within the synchronized area Puts thread that calls it into the WAITING state 1) Some other thread calls notify() or notifyAll() 2) The thread actually reacquires the lock (remember that it is already within the synchronized area) > notify() will awaken 1 wait()ing thread on that lock (cannot specify which one) > notifyAll() will awaken all wait()ing threads on that lock > No guarantee that this will happen right away 25 Lecture 4: More on Threads Note that even after a thread has reacquired the lock, the condition that caused it to call wait() in the first place may still exist! > Only one can get the item > Others might go right back and call wait() again For example, multiple Consumers are waiting on a single Producer See Niemeyer text and Consumer.java handout However, this is more efficient than having a spin/test loop without wait(), since a Thread will only be notify()ed if there is some reason to do so (i.e. the condition for waiting has changed) 26 Lecture 4: More on Threads 4 As mentioned in Consumer.java, a shortcoming of wait() / notify() is that you cannot notify() specific Threads It is either notify() one arbitrarily selected Thread or notifyAll() Threads 4 In JDK 1.5 an alternative synchronization mechanism was introduced This includes the Lock and Condition interfaces which give somewhat more flexibility to handling concurrent Threads However, it is also more syntactically complex and allows for more programming error 27 Lecture 4: More on Threads The basic idea is that rather than the implicit locking / unlocking that is associated with synchronized methods and blocks, we can now explicitly lock and unlock objects Benefit: We now must explicitly associate the Lock objects with the code we want to protect The Condition interface allows for different queues on the same Lock, each of which can be signaled separately We can wake up only the relevant Threads (waiting on a specific condition) for a given Lock > This saves a lot of computation, since unnecessary Threads are not awakened (and then spin and go right back to sleep) 28 Lecture 4: More on Threads Drawback: Let's look at the Consumer/Producer program using this alternative mechanism See ConsumerB.java (especially. comments) The locks are not automatically given up when the critical area is exited (as is the case with synchronized methods and blocks) If we forget to release the lock (i.e. have a bug in our code) it can cause serious problems, since no other Thread will be able to obtain that lock 29 Lecture 4: More on Threads 4 It is clear that programming with synchronized data can be complicated 4 We must be careful to avoid: deadlock: no thread can proceed due to interdependencies starvation: one or more threads never proceed while others do Ex. Be sure there is a notify() corresponding to each wait(), or unlock() for each lock() This is not always easy to do Famous example: Dining philosophers 30 Lecture 4: More on Threads 4 However, you don't have to overdo it either If you synchronize Threads that don't really need it, you are just slowing down program execution If notify() or notifyAll() are called when they are not needed, threads will wake up and then just wait() again, wasting CPU cycles See again Consumer.java and ctr variable 31 Lecture 4: More on Threads Additional notes on Threads 4 Java does not guarantee that timeslicing be used to manage Thread scheduling Thus you should not depend on this to fairly switch between same priority ready, CPUintensive threads The yield() method allows a thread to voluntarily give up the CPU It is still READY, just not RUNNING anymore It will immediately contend for the CPU again 4 The wait() method can also be called with a long argument Will wake up if not notified prior to time amount 32 Lecture 4: More on Threads Remember that stop(), suspend() and resume() are deprecated stop() releases any locks a thread may have If thread was in the middle of a critical area, the object it was modifying may be in an inconsistent (damaged state) Much better to adjust variables so that thread dies gracefully If not resume()d, other threads waiting on the locks will never be able to run Can lead to deadlock or starvation suspend() does NOT release locks a thread may have 33 Lecture 5: Intro. to Java Networking The Java language supports intercomputer communication in many ways 4 Applets (Niemeyer Ch. 22, Sebesta Ch. 7) Java programs can be run remotely via Web Browsers 4 Servlets and JSP (Niemeyer Ch. 14, Sebesta Ch. 11) Servlets allow Java programs to handle what had prev. been done with scripts (ex. Perl) Ex. Processing forms from a Web page Java Server Pages allow Java to be interleaved with HTML, similar to what we will see in PHP We may come back to these if we have time 34 4 Remote Method Invocation (Niemeyer p. 355) Lecture 5: Intro. to Java Networking Allow Java objects to be accessed remotely Server object resides on one machine Client program accesses methods of server object (almost) as if object is local connection protocols handled transparently Transfer Protocol (HTTP) Java class URL can store and access URLs 4 Manipulating URLs Uniform Resource Locators (URLs) are used by the HyperText Access URLs to build Web Browsers in Java (see p. 506 in Niemeyer) Each Java Applet has an AppletContext Very Very Very Simple Example: Parameters allow interaction with html file 35 > Interface that allows access to the browser displaying the applet > showDocument() method replaces current document with one specified in URL argument Lecture 5: Intro. to Java Networking import java.awt.*; import java.net.*; import java.applet.*; public class urldemo extends Applet { URL myurl = null; public void init() { try {myurl = new URL("http://www.cs.pitt.edu/~ramirez");} catch (MalformedURLException e) { e.printStackTrace(); } } public void start() { showStatus("You are about to be forwarded to a new site"); try { Thread.sleep(4000); } catch (InterruptedException e) {} AppletContext appl = getAppletContext(); appl.showDocument(myurl); } } 36 Lecture 5: Intro. to Java Networking 4 Sockets Originated in UNIX to allow lowlevel network communication Since different networks have different protocols, UNIX sockets are somewhat complex to use In Java, the lowlevel protocols are transparent to the programmer IP (Internet Protocol) supported TCP (Transmission Control Protocol) is used for Sockets Fairly standard these days 37 Java Sockets (see Niemeyer Ch. 12) Lecture 5: Intro. to Java Networking 4 Sockets use a connectionoriented protocol (TCP) Logically, the idea is similar to using the phone Client connects to server, then commun. (twoway) can occur across the connection Connection remains even if no data is transferred Logically, at least physically the underlying TCP/IP does not maintain a connection Ensures that no data is lost and always arrives in correct order But takes time to set up not good for short transmissions See: 38 http://java.sun.com/docs/books/tutorial/networking/sockets/index.html Lecture 5: Intro. to Java Networking 4 Java also supports DatagramSockets This is a connectionless protocol Packets are sent back and forth between server and client Individual packets are addressed so they can be delivered correctly (ex. like US mail) But no guarantee that all packets will arrive (like mail) and no guarantee that ordering will be maintained More tolerant to failure, faster for short communications See: Up to programmer to deal with these issues http://java.sun.com/docs/books/tutorial/networking/datagrams/index.html 39 Lecture 5: Intro. to Java Networking Using Java Sockets 4 Two important classes: ServerSocket allows connections to be established to server waits on accept() method until connection is granted resides on the machine on which the server program is being executed > Typically has some IP address > Usually accessed by name waits on a PORT (integer id) 40 Ex: unixs1.cis.pitt.edu Ex: nomad.cs.pitt.edu Lecture 5: Intro. to Java Networking Socket used on both sides of a server/client connection Client connects to server by creating a new Socket, supplying Server's IP address and port number Server accepts Socket from the Client On both ends > If you are testing your program locally, or if your machine is not connected to the internet, you can use "localhost" See JRServer.java and ex16.java 41 Server's OutputStream is client's InputStream Server's InputStream is client's OutputStream simple or complex data can be transferred > contains an InputStream and an OutputStream Lecture 5: Java Sockets Let's look at a another example 4 Server will wait for connection from clients 4 At each connection, client will send a single message to the server, which the server will print 4 Server sends no data back to the client SendToMe.java ISend.java will accept clients one at a time, printing a single message from each will connect to the server, passing a single message to it, then terminate 42 Lecture 5: Java Sockets To send a message from the second prompt to the first, type the following at the command prompt: instead of localhost put the host's name Ex: unixs1.cis.pitt.edu java ISend localhost yourname "your message" If you want to send a message to another host, Let's look at the code 43 Class 5: Two-Way Communication In the previous example 4 Client sends, server receives What if both client and server want to send and receive data? 4 If sending and receiving are synchronized, we do 4 Server has simple loop, client a few lines not have to complicate things much 4 What if server and client want to be able to send to each other at any time? 4 We need to use Threads 44 Class 5: Two-Way Communication Both sides of the communication must be ready to send or receive a message at any time 4 Without Threads, they could end up CLIENT deadlocked Client trying to read message from server Server trying to read message from client 45 SERVE R Class 5: Two-Way Communication We need a way for each side to accept and receive messages at any time 4 One Thread for reading 4 One Thread for writing CLIENT Client Thread waiting to accept messages Server Thread sending messages Client Thread sending messages 46 Server Thread waiting to accept messages SERVE R Class 5: Two-Way Communication Look at next example 4 TwoWayServer.java Run with user's name on command line 4 TwoWayClient.java Run with server name and client name java TwoWayServer username This will connect client to server and connection will remain until terminated by one party or the other java TwoWayClient servername clientname If not on the net servername will be localhost 47 Class 5: Two-Way Communication Let's look at the code 4 Note that both programs look similar Threads are created for the input stream and for the output stream Each runs until the client/server has quit 4 The threads are NOT synchronized (no monitors used) Could cause a problem, but in this simple example it is not absolutely necessary If we have more complicated communication, monitors will be definitely required Could lead to data consistency problems otherwise 48 ...
View Full Document

Ask a homework question - tutors are online