Chapter 3: A Larger Example: SocketChat

Size: px
Start display at page:

Download "Chapter 3: A Larger Example: SocketChat"

Transcription

1 page 1 Chapter 3: A Larger Example: SocketChat In this chapter we are going to look at three versions of a larger socket-based example: a simple `chat' application. The application does not have many capabilities, and the implementation would not scale up very well to large numbers of clients. But it does illustrate a number of issues. You can download the code: The The Client source. The The Server source. The The Message object class. We are going to consider three versions of this application, all of which differ only in how the server is implemented. The first version is wrong, and illustates a common error. The second corrects it and works correctly; the third gets rid of an obvious inefficiency Client The client consists only of two scrollable text panes: one containing text you type, the other text typed by others. The first line of text you type is your name - you can't change it afterwards and it doesn't have to be unique (I said it was basic). The user interface is based on the Swing API. To send a message, just type text (making sure the input textarea has focus - we could fix that programatically) and hit return. Note that strictly we're breaking some rules here since we're using multiple threads with a Swing interface. Swing is not inherently thread safe, and you're supposed to use special techniques to build threaded Swing applications. However, since our second thread is exclusively in control of one GUI component, we're very unlikely to have trouble (that's my excuse anyway). Here's the first chunk of code, leaving out the import statements (check the actual source file): import java.io.*; import java.net.*; import javax.swing.*; public class AppChatClient { private void initcomponents(string host) { mytext.addkeylistener(new java.awt.event.keyadapter() { public void keytyped(java.awt.event.keyevent evt) { texttyped(evt); ); Socket mysocket = new Socket(host, Message.getSocketNumber()); othertextthread = new TextThread(otherText, mysocket); OutputStream temp = mysocket.getoutputstream(); out = new ObjectOutputStream(temp); othertextthread.start(); frame.addwindowlistener(new WindowAdapter() { );

2 page 2 catch (Exception ex) { othertext.append("failed to connect to server."); private void texttyped(java.awt.event.keyevent evt) { public static void main(string[] args) { if (args.length < 1) { System.out.println("Usage: AppChatClient host"); return; final String host = args[0]; javax.swing.swingutilities.invokelater(new Runnable() { AppChatClient client = new AppChatClient(); public void run() { client.initcomponents(host); ); The main method creates all the user-interface components by calling initcomponents() (the javax.swing.swingutilities.invokelater stuff just makes sure the GUI gets started in the event handling thread, it's not important here; and the frame.addwindowlistener stuff just makes sure that an exit message is sent to the server when the client closes). initcomponents also sets up the socket. Rather than hard-code the socket hostname/ip address in the source, it's passed in as a command-line parameter. Similarly, the socket number is not hard-coded in the client, but is in the Message class, used to pass messages between client and server (and which is therefore available to both). Next an object output stream is attached to the socket. This will allow us to send complete Java objects between the server and client. This is a somewhat more sophisticated solution than just sending strings, but does mean that it is more difficult for us to make the server and client language independent. A more flexible alternative would be to use XML - which is one of the ideas behind XML Web Services. More on them later in the module. Next, it creates and starts a thread of the class TextThread. We will look at this later in the chapter, but briefly we need it because messages from other clients may arrive (via the server) at any time, and we need a separate thread to read and display them. Strictly, because the GUI is already in another thread, we could get away without doing this - but doing so makes it explicit, and clearer (to me, anyway). The rest of the client is made up of three methods. The first, initcomponents() is mainly concerned with setting up the GUI, and we will not show all of it. The only interesting bit is: mytext.addkeylistener(new java.awt.event.keyadapter() { public void keytyped(java.awt.event.keyevent evt) { texttyped(evt); ); which adds a key listener, directing keyboard events to the method texttyped. texttyped is the next method: private void texttyped(java.awt.event.keyevent evt) { char c = evt.getkeychar(); if (c == '\n'){ Message m; if (firstmessage) {

3 page 3 m = new Message(Message.NAME_MESSAGE,textString); firstmessage = false; name = textstring; else { m = new Message(Message.NORMAL_MESSAGE,textString); out.writeobject(m); catch (IOException ie) { othertext.append("failed to send message."); textstring = ""; else { // In general, this is not efficient - // StringBuffer is better // but efficiency is not really an issue here. textstring = textstring + c; Everytime a key is pressed, this is called. If the key is not a carriage return, then we simply append the character to textstring. Otherwise, we create a Message object, including the text string, and send it to the server using the ObjectOutputStream class' method writeobject. If this is the first message from this client, then the message type is NAME_MESSAGE; otherwise it's NORMAL_MESSAGE. The remaining class in the client is the very simple TextThread: class TextThread extends Thread { ObjectInputStream in; JTextArea othertext; Socket socket; TextThread(JTextArea other, Socket mysocket) throws IOException { othertext = other; socket = mysocket; public void run() { in = new ObjectInputStream(socket.getInputStream()); while (true) { Object message = in.readobject(); if ((message == null) (!(message instanceof Message))){ othertext.append("error reading from server."); return; Message m = (Message)message; switch (m.gettype()) { case Message.NORMAL_MESSAGE: othertext.append(m.getmessage()); case Message.NAME_MESSAGE: othertext.append(m.getmessage() + " has joined."); case Message.EXIT_MESSAGE: othertext.append(m.getmessage() + " has left the building."); default: othertext.append("error reading from server."); othertext.append("\n");

4 page 4 catch (Exception e) { othertext.append("error reading from server."); return; The constructor attaches an ObjectReader to the socket, and then continually reads objects sent by the server, extracting and displaying the actual message (details depending on the message type) Communicating: Messages The clients and server communicate by sending Message objects to each other. This is arguably a bit inefficient, and a simple string would be enough (when I used to set this as coursework, nearly everyone sent strings). Using objects does make it easier to send other information (we send a message type integer), and also makes it easier to make changes (strictly, if you are careful with the code, this can be true of just sending strings). public class Message implements Serializable { private static final long serialversionuid = 42L; private static final int SOCKET_NUMBER = 1664; public static final int EXIT_MESSAGE = 0; public static final int NAME_MESSAGE = 1; public static final int NORMAL_MESSAGE = 2; public static final int INVALID_MESSAGE = -1; private final String message; private final int type; public Message(int t, String m) { message = m; type = t; public static int getsocketnumber() { return SOCKET_NUMBER; public String getmessage() { return message; public int gettype() { return type; This should be pretty straightforward - there's a constructor and accessor methods for the two private fields, as well as constants for the message types identified so far. Slightly controversial is the inclusion of SOCKET_NUMBER (and it's accessor) here. Normally, I put all global(ish) constants in a separate class, with an accessor (having an accessor makes it easier to change them later from simple constants - to, say, database entries). However in this case there is only one such constant and it seems a bit excessive to have a class for it Servers: Common Code Server versions 1 and two differ only in one method, and version 3 only by one method and a class, so we can save ourselves a lot of code by using an abstract class and interfaces. It's debatable if this actually makes it easier to read or not (and I'm not going to do it in the RMI Version. But I think sometimes that not everyone is convinced of the usefulness of concepts like abstract classes and interfaces, and an illustrative example is quite useful. interface IsServerThread extends Runnable {

5 page 5 public void writemessage(message message); We will inplement this interface with an abstract class ServerThread, and then subclass this with ServerThread1, ServerThread2 and ServerThread3, which provide different implementations of the one abstract method propagate (not the one in the interface, notice). Strictly, the interface is not necessary but in general it is good practice. The interface extends runnable interface, so any implementation of IsServerThread can run as a thread. The following interface and class are only needed to incorporate version 3 along with 1 and 2 - for 1 and 2 we could just get away with any Collection object. interface IsServerList { public void add(isserverthread item); public void remove(isserverthread item); public void inccounter(); public void deccounter(); public Collection getcollection(); All versions will store client threads in objects that implement the IsServerList interface. The first two versions don't need the counter methods, so BasicServerList below just encapsulates an ArrayList (though note we can replace it with any Collection object. The getcollection method extracts the encapsulated Collection object - easier than implementing Collection, returning it's own iterator etc., etc. class BasicServerList implements IsServerList { private Collection<IsServerThread> threadlist = new ArrayList<IsServerThread>(); public void add(isserverthread item) { threadlist.add(item); public void remove(isserverthread item) { threadlist.remove(item); public void inccounter() { public void deccounter() { //Note it is *not* a bug that it isn't synchronized public Collection getcollection() { return threadlist; Here is the important part of the main method: ServerSocket ssoc = null; ssoc = new ServerSocket(Message.getSocketNumber()); catch (IOException e) {

6 page 6 //Use BasicServerList for versions 1 and 2, ServerList for 3 //IsServerList serverlist = new BasicServerList(); IsServerList serverlist = new ServerList(); while(true) { Socket insoc = ssoc.accept(); //Uncomment the appropriate lines to switch implementations /*IsServerThread newserverthread = new ServerThread1(inSoc, serverlist);*/ /*IsServerThread newserverthread = new ServerThread2(inSoc, serverlist);*/ IsServerThread newserverthread = new ServerThread3(inSoc, serverlist); new Thread(newServerThread).start(); catch (IOException e) { We create a ServerSocket, then wait for connections. Each connection results in a new thread being started. The only interesting lines are IsServerThread newserverthread = new ServerThread?(inSoc); and IsServerList serverlist = new [Basic]ServerList(); where we use the interfaces The Abstract Class Here is the abstract class: abstract class ServerThread implements IsServerThread { protected static IsServerList threadlist; private ObjectInputStream in; private ObjectOutputStream out; private String name; { public ServerThread(Socket insoc, IsServerList list) throws IOException threadlist = list; in = new ObjectInputStream(inSoc.getInputStream()); out = new ObjectOutputStream(inSoc.getOutputStream()); synchronized (threadlist) { threadlist.add(this); public void run(){ boolean notfinished = true; while (notfinished) { Object rawmessage = in.readobject(); if (!(rawmessage instanceof Message)) {

7 page 7 Message message = (Message)rawMessage; //This could represent a client that has //exited if (message == null) { notfinished = false; switch (message.gettype()){ case Message.NORMAL_MESSAGE: case Message.NAME_MESSAGE: propagate(message); case Message.EXIT_MESSAGE: propagate(message); notfinished = false; default: //Ignore any other values - they are errors. Thread.yield(); //In case we don't have native threads catch (IOException ie) { System.out.println("IO Exception"); ie.printstacktrace(); catch (ClassNotFoundException cnfe) { //Clean up finally { synchronized (threadlist) { threadlist.remove(this); //Write out to this thread's client public void writemessage(message message) { if (message == null) { System.out.println("Null message"); else { out.writeobject(message); catch (Exception e) { abstract protected void propagate(message message); There are three methods and a constructor. Constructor. The constructor attaches input and output object streams to the socket connected to the client, and adds an instance of itself to a Collection object. This final action is synchronized - we need to protect access to the Collection thread list. We could have used the already-synchronized Vector, instead of ArrayList. However, this would have constrained our options later on. run.the run method is required, since ServerThread implements Runnable. This method does most of the work: reading objects, making sure they are Message objects, and then deciding what to do with them. The finally clause is executed as the method exits, and it removes itself from the thread list (also synchronized).

8 page 8 writemessage. This handles the low level details of actually sending an object to an individual client. propagate. This is the abstract method. It will be responsible for distributing a message to all active clients (by calling writemessage). This contains multiple instances of the use of interfaces. We are using the interface IsServerThread to determine what can be stored in the ArrayList. We also use Collection so we can trivially replace ArrayList with some other implemenation of Collection. Both of these steps make later code changes easier The First Wrong Server Version Our first implementation has a subtle error. It contains the same error that occurs if you simply use Vector instead of ArrayList and think that because Vector's synchronized, all your problems are over. However, synchronization issues are usually more complex than that. class ServerThread2 extends ServerThread { public ServerThread2(Socket insoc) throws IOException { super(insoc); protected void propagate(message message) { for (Iterator i = threadlist.iterator(); i.hasnext();) { synchronized (threadlist) { IsServerThread thread = (IsServerThread)i.next(); thread.writemessage(message); This version synchronizes each individual (more or less) access to the thread list. The problem with this is that although access to the thread list is protected, there may be other threads being created/destroyed while the for loop is running. So the thread list may change during the loop. This is not guaranteed to work, or even not lead to serious failure. (In general, this is true for most for loops - they generally compute the loop bounds before they start, and then changing them during the loop is not a good idea. Are you likely to see this? This is a toy example, and with only a small number of clients then no, it's not likely. But in a real application with many clients, this problem will inevitably occur The Second Correct Server Version The solution is simple - just synchronize the whole loop: class ServerThread1 extends ServerThread { // Constructor as before protected void propagate(message message) { synchronized (threadlist) { for (Iterator i = threadlist.iterator(); i.hasnext();) { IsServerThread thread = (IsServerThread)i.next(); thread.writemessage(message); Although the server will now work properly, it does look a little inefficient (though working and inefficient is always better than not working). We only really want to synchronize access to the thread list on write operations, and prevent write operations when read operations are in progress. Multiple simultaneous reads are OK. Our current implementation however only allows a single operation (read or write) to occur simultaneously. The next version addresses this.

9 page Third (Possible) Version - Cloning A possible third approach, which we won't code, and which may be more efficient, is to clone the thread list before we send messages out to clients. This isn't as inefficient as it seems, because the copy is shallow - that is, it only copies the references to the threads, not the thread objects themselves. We don't include the code for this because we cannot use our existing abstract class - it only requires that the structure used to store the thread list implements Collection, and the clone() method is in Cloneable (ArrayList implements both). The required changes are small though, so feel free to have a go yourself Third (Actual) Version - Partial Synchronization In this version, we will develop a version that synchronizes access to the thread list only on write operations (adding, deleting threads). All read operations can proceed unsynchronized - though we also make sure that no writes can occur when reads are in progress. To start with, we need a new thread storage class. class ServerList implements IsServerList { private Collection<IsServerThread> threadlist = new ArrayList<IsServerThread>(); private int counter = 0; public synchronized void add(isserverthread item) { while (counter > 0) { wait(); threadlist.add(item); catch (InterruptedException e) { System.out.println("Addition interrupted."); finally{ notifyall(); public synchronized void remove(isserverthread item) { while (counter > 0) { wait(); threadlist.remove(item); catch (InterruptedException e) { System.out.println("Removal interrupted."); finally { notifyall(); // Similarly for changing counter public synchronized void inccounter() { counter++; notifyall(); public synchronized void deccounter() { counter--; notifyall(); public Collection getcollection() { return threadlist;

10 page 10 The add and remove methods are synchronized so only one can proceed at a time - but that in itself is not sufficient. So we also add a counter, to keep track of the number of ongoing read operations. Before starting a read operation (that is, we propagate a message to clients) we increment the counter, and when finished we decrement it - and notice that the act of incrementing/decrementing the counter is also synchronized. We can only add/remove clients when the counter is zero. Let's look at the code of one method (the other is similar: while (counter > 0) { wait(); threadlist.remove(item); catch (InterruptedException e) { finally { notifyall(); If the counter is non-zero, the method waits - i.e. sleeps, giving up the synchronization lock. It will only be woken when one of the other methods calls notifyall(), when it will check the counter again. Eventually, the counter will be zero and the method will proceed. The call to notifayall() will wake all other sleeping threads, which can then check to see if they can proceed. Here's the code for propagate: class ServerThread3 extends ServerThread { public ServerThread3(Socket insoc, IsServerList list) throws IOException { super(insoc, list); protected void propagate(message message) { threadlist.inccounter(); for (Iterator i = threadlist.getcollection().iterator(); i.hasnext();) { IsServerThread thread = (IsServerThread)i.next(); thread.writemessage(message); threadlist.deccounter();

Reading from URL. Intent - open URL get an input stream on the connection, and read from the input stream.

Reading from URL. Intent - open URL  get an input stream on the connection, and read from the input stream. Simple Networking Loading applets from the network. Applets are referenced in a HTML file. Java programs can use URLs to connect to and retrieve information over the network. Uniform Resource Locator (URL)

More information

CMSC 132: Object-Oriented Programming II. Threads in Java

CMSC 132: Object-Oriented Programming II. Threads in Java CMSC 132: Object-Oriented Programming II Threads in Java 1 Problem Multiple tasks for computer Draw & display images on screen Check keyboard & mouse input Send & receive data on network Read & write files

More information

What is Serialization?

What is Serialization? Serialization 1 Topics What is Serialization? What is preserved when an object is serialized? Transient keyword Process of serialization Process of deserialization Version control Changing the default

More information

Chapter 2. Network Chat

Chapter 2. Network Chat Chapter 2. Network Chat In a multi-player game, different players interact with each other. One way of implementing this is to have a centralized server that interacts with each client using a separate

More information

AP COMPUTER SCIENCE JAVA CONCEPTS IV: RESERVED WORDS

AP COMPUTER SCIENCE JAVA CONCEPTS IV: RESERVED WORDS AP COMPUTER SCIENCE JAVA CONCEPTS IV: RESERVED WORDS PAUL L. BAILEY Abstract. This documents amalgamates various descriptions found on the internet, mostly from Oracle or Wikipedia. Very little of this

More information

Multitasking Multitasking allows several activities to occur concurrently on the computer. A distinction is usually made between: Process-based multit

Multitasking Multitasking allows several activities to occur concurrently on the computer. A distinction is usually made between: Process-based multit Threads Multitasking Multitasking allows several activities to occur concurrently on the computer. A distinction is usually made between: Process-based multitasking Thread-based multitasking Multitasking

More information

A Quick Tour p. 1 Getting Started p. 1 Variables p. 3 Comments in Code p. 6 Named Constants p. 6 Unicode Characters p. 8 Flow of Control p.

A Quick Tour p. 1 Getting Started p. 1 Variables p. 3 Comments in Code p. 6 Named Constants p. 6 Unicode Characters p. 8 Flow of Control p. A Quick Tour p. 1 Getting Started p. 1 Variables p. 3 Comments in Code p. 6 Named Constants p. 6 Unicode Characters p. 8 Flow of Control p. 9 Classes and Objects p. 11 Creating Objects p. 12 Static or

More information

Handouts. 1 Handout for today! Recap. Homework #2 feedback. Last Time. What did you think? HW3a: ThreadBank. Today. Small assignment.

Handouts. 1 Handout for today! Recap. Homework #2 feedback. Last Time. What did you think? HW3a: ThreadBank. Today. Small assignment. Handouts CS193J: Programming in Java Summer Quarter 2003 Lecture 10 Thread Interruption, Cooperation (wait/notify), Swing Thread, Threading conclusions 1 Handout for today! #21: Threading 3 #22: HW3a:

More information

Threads Chate Patanothai

Threads Chate Patanothai Threads Chate Patanothai Objectives Knowing thread: 3W1H Create separate threads Control the execution of a thread Communicate between threads Protect shared data C. Patanothai Threads 2 What are threads?

More information

830512@itri.org.tw import java.net.socket; import java.net.serversocket; import java.io.ioexception; /* ---------- Java Server ---------- */ public class Nets static Socket thesocket; static ServerThread

More information

Java Threads. Introduction to Java Threads

Java Threads. Introduction to Java Threads Java Threads Resources Java Threads by Scott Oaks & Henry Wong (O Reilly) API docs http://download.oracle.com/javase/6/docs/api/ java.lang.thread, java.lang.runnable java.lang.object, java.util.concurrent

More information

Info 408 Distributed Applications Programming Exercise sheet nb. 4

Info 408 Distributed Applications Programming Exercise sheet nb. 4 Lebanese University Info 408 Faculty of Science 2017-2018 Section I 1 Custom Connections Info 408 Distributed Applications Programming Exercise sheet nb. 4 When accessing a server represented by an RMI

More information

/* Copyright 2012 Robert C. Ilardi

/* Copyright 2012 Robert C. Ilardi / Copyright 2012 Robert C. Ilardi Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at

More information

G52CON: Concepts of Concurrency

G52CON: Concepts of Concurrency G52CON: Concepts of Concurrency Lecture 11: Semaphores I" Brian Logan School of Computer Science bsl@cs.nott.ac.uk Outline of this lecture" problems with Peterson s algorithm semaphores implementing semaphores

More information

7. MULTITHREDED PROGRAMMING

7. MULTITHREDED PROGRAMMING 7. MULTITHREDED PROGRAMMING What is thread? A thread is a single sequential flow of control within a program. Thread is a path of the execution in a program. Muti-Threading: Executing more than one thread

More information

CPSC 441 Tutorial TCP Server. Department of Computer Science University of Calgary

CPSC 441 Tutorial TCP Server. Department of Computer Science University of Calgary CPSC 441 Tutorial TCP Server Department of Computer Science University of Calgary TCP Socket Client Server Connection Request Server Listening on welcoming socket Client Socket Server Socket Data Simple

More information

CS 2112 Lecture 20 Synchronization 5 April 2012 Lecturer: Andrew Myers

CS 2112 Lecture 20 Synchronization 5 April 2012 Lecturer: Andrew Myers CS 2112 Lecture 20 Synchronization 5 April 2012 Lecturer: Andrew Myers 1 Critical sections and atomicity We have been seeing that sharing mutable objects between different threads is tricky We need some

More information

School of Informatics, University of Edinburgh

School of Informatics, University of Edinburgh CS1Bh Solution Sheet 4 Software Engineering in Java This is a solution set for CS1Bh Question Sheet 4. You should only consult these solutions after attempting the exercises. Notice that the solutions

More information

1 Shyam sir JAVA Notes

1 Shyam sir JAVA Notes 1 Shyam sir JAVA Notes 1. What is the most important feature of Java? Java is a platform independent language. 2. What do you mean by platform independence? Platform independence means that we can write

More information

12% of course grade. CSCI 201L Final - Written Fall /7

12% of course grade. CSCI 201L Final - Written Fall /7 12% of course grade 1. Interfaces and Inheritance Does the following code compile? If so, what is the output? If not, why not? Explain your answer. (1.5%) interface I2 { public void meth1(); interface

More information

Threads and Locks. CSCI 5828: Foundations of Software Engineering Lecture 09 09/22/2015

Threads and Locks. CSCI 5828: Foundations of Software Engineering Lecture 09 09/22/2015 Threads and Locks CSCI 5828: Foundations of Software Engineering Lecture 09 09/22/2015 1 Goals Cover the material presented in Chapter 2, Day 1 of our concurrency textbook Creating threads Locks Memory

More information

List ADT. Announcements. The List interface. Implementing the List ADT

List ADT. Announcements. The List interface. Implementing the List ADT Announcements Tutoring schedule revised Today s topic: ArrayList implementation Reading: Section 7.2 Break around 11:45am List ADT A list is defined as a finite ordered sequence of data items known as

More information

Lecture 9: Introduction to Monitors

Lecture 9: Introduction to Monitors COMP 150-CCP Concurrent Programming Lecture 9: Introduction to Monitors Dr. Richard S. Hall rickhall@cs.tufts.edu Concurrent programming February 14, 2008 Abstracting Locking Details Recall our discussion

More information

Multiple Choice Questions: Identify the choice that best completes the statement or answers the question. (15 marks)

Multiple Choice Questions: Identify the choice that best completes the statement or answers the question. (15 marks) M257 MTA Spring2010 Multiple Choice Questions: Identify the choice that best completes the statement or answers the question. (15 marks) 1. If we need various objects that are similar in structure, but

More information

/** * Created Aug 19, 2012 */ package com.roguelogic.util;

/** * Created Aug 19, 2012 */ package com.roguelogic.util; / Copyright 2012 Robert C. Ilardi Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at

More information

Java s Implementation of Concurrency, and how to use it in our applications.

Java s Implementation of Concurrency, and how to use it in our applications. Java s Implementation of Concurrency, and how to use it in our applications. 1 An application running on a single CPU often appears to perform many tasks at the same time. For example, a streaming audio/video

More information

CS193k, Stanford Handout #8. Threads 3

CS193k, Stanford Handout #8. Threads 3 CS193k, Stanford Handout #8 Spring, 2000-01 Nick Parlante Threads 3 t.join() Wait for finish We block until the receiver thread exits its run(). Use this to wait for another thread to finish. The current

More information

Java Threads. COMP 585 Noteset #2 1

Java Threads. COMP 585 Noteset #2 1 Java Threads The topic of threads overlaps the boundary between software development and operation systems. Words like process, task, and thread may mean different things depending on the author and the

More information

Java Support for developing TCP Network Based Programs

Java Support for developing TCP Network Based Programs Java Support for developing TCP Network Based Programs 1 How to Write a Network Based Program (In Java) As mentioned, we will use the TCP Transport Protocol. To communicate over TCP, a client program and

More information

THIS EXAMINATION PAPER MUST NOT BE REMOVED FROM THE EXAMINATION ROOM

THIS EXAMINATION PAPER MUST NOT BE REMOVED FROM THE EXAMINATION ROOM UNIVERSITY OF LONDON GOLDSMITHS COLLEGE B. Sc. Examination 2012 COMPUTER SCIENCE IS52025A Internet and Distributed Programming Duration: 2 hours 15 minutes Date and time: There are five questions in this

More information

ICOM 4015-Advanced Programming. Spring Instructor: Dr. Amir H. Chinaei. TAs: Hector Franqui, Jose Garcia, and Antonio Tapia. Reference: Big Java

ICOM 4015-Advanced Programming. Spring Instructor: Dr. Amir H. Chinaei. TAs: Hector Franqui, Jose Garcia, and Antonio Tapia. Reference: Big Java ICOM 4015-Advanced Programming Spring 2014 Instructor: Dr. Amir H. Chinaei TAs: Hector Franqui, Jose Garcia, and Antonio Tapia Reference: Big Java By Hortsmann, Ed 4 Lab 7 Continuation of HTTP and Introduction

More information

What is a thread anyway?

What is a thread anyway? Concurrency in Java What is a thread anyway? Smallest sequence of instructions that can be managed independently by a scheduler There can be multiple threads within a process Threads can execute concurrently

More information

CS11 Java. Fall Lecture 7

CS11 Java. Fall Lecture 7 CS11 Java Fall 2006-2007 Lecture 7 Today s Topics All about Java Threads Some Lab 7 tips Java Threading Recap A program can use multiple threads to do several things at once A thread can have local (non-shared)

More information

The Dining Philosophers Problem CMSC 330: Organization of Programming Languages

The Dining Philosophers Problem CMSC 330: Organization of Programming Languages The Dining Philosophers Problem CMSC 0: Organization of Programming Languages Threads Classic Concurrency Problems Philosophers either eat or think They must have two forks to eat Can only use forks on

More information

School of Informatics, University of Edinburgh

School of Informatics, University of Edinburgh CS1Ah Lecture Note 29 Streams and Exceptions We saw back in Lecture Note 9 how to design and implement our own Java classes. An object such as a Student4 object contains related fields such as surname,

More information

Network. Dr. Jens Bennedsen, Aarhus University, School of Engineering Aarhus, Denmark

Network. Dr. Jens Bennedsen, Aarhus University, School of Engineering Aarhus, Denmark Network Dr. Jens Bennedsen, Aarhus University, School of Engineering Aarhus, Denmark jbb@ase.au.dk Outline Socket programming If we have the time: Remote method invocation (RMI) 2 Socket Programming Sockets

More information

Exercise Session Week 8

Exercise Session Week 8 Chair of Software Engineering Java and C# in Depth Carlo A. Furia, Marco Piccioni, Bertrand Meyer Exercise Session Week 8 Quiz 1: What is printed? (Java) class MyTask implements Runnable { public void

More information

G51PGP Programming Paradigms. Lecture 009 Concurrency, exceptions

G51PGP Programming Paradigms. Lecture 009 Concurrency, exceptions G51PGP Programming Paradigms Lecture 009 Concurrency, exceptions 1 Reminder subtype polymorphism public class TestAnimals public static void main(string[] args) Animal[] animals = new Animal[6]; animals[0]

More information

CS 351 Design of Large Programs Threads and Concurrency

CS 351 Design of Large Programs Threads and Concurrency CS 351 Design of Large Programs Threads and Concurrency Brooke Chenoweth University of New Mexico Spring 2018 Concurrency in Java Java has basic concurrency support built into the language. Also has high-level

More information

CMSC 330: Organization of Programming Languages. The Dining Philosophers Problem

CMSC 330: Organization of Programming Languages. The Dining Philosophers Problem CMSC 330: Organization of Programming Languages Threads Classic Concurrency Problems The Dining Philosophers Problem Philosophers either eat or think They must have two forks to eat Can only use forks

More information

Multiple Inheritance. Computer object can be viewed as

Multiple Inheritance. Computer object can be viewed as Multiple Inheritance We have seen that a class may be derived from a given parent class. It is sometimes useful to allow a class to be derived from more than one parent, inheriting members of all parents.

More information

CS 162 Operating Systems and Systems Programming Professor: Anthony D. Joseph Spring 2002

CS 162 Operating Systems and Systems Programming Professor: Anthony D. Joseph Spring 2002 CS 162 Operating Systems and Systems Programming Professor: Anthony D. Joseph Spring 2002 Lecture 6: Synchronization 6.0 Main points More concurrency examples Synchronization primitives 6.1 A Larger Concurrent

More information

CMSC 330: Organization of Programming Languages. Threads Classic Concurrency Problems

CMSC 330: Organization of Programming Languages. Threads Classic Concurrency Problems : Organization of Programming Languages Threads Classic Concurrency Problems The Dining Philosophers Problem Philosophers either eat or think They must have two forks to eat Can only use forks on either

More information

Problems with Concurrency. February 19, 2014

Problems with Concurrency. February 19, 2014 with Concurrency February 19, 2014 s with concurrency interleavings race conditions dead GUI source of s non-determinism deterministic execution model 2 / 30 General ideas Shared variable Access interleavings

More information

Threads and Parallelism in Java

Threads and Parallelism in Java Threads and Parallelism in Java Java is one of the few main stream programming languages to explicitly provide for user-programmed parallelism in the form of threads. A Java programmer may organize a program

More information

Exercise Session Week 8

Exercise Session Week 8 Chair of Software Engineering Java and C# in Depth Carlo A. Furia, Marco Piccioni, Bertrand Meyer Exercise Session Week 8 Java 8 release date Was early September 2013 Currently moved to March 2014 http://openjdk.java.net/projects/jdk8/milestones

More information

CMSC 330: Organization of Programming Languages

CMSC 330: Organization of Programming Languages CMSC 330: Organization of Programming Languages Threads Synchronization Refers to mechanisms allowing a programmer to control the execution order of some operations across different threads in a concurrent

More information

Casting -Allows a narrowing assignment by asking the Java compiler to "trust us"

Casting -Allows a narrowing assignment by asking the Java compiler to trust us Primitives Integral types: int, short, long, char, byte Floating point types: double, float Boolean types: boolean -passed by value (copied when returned or passed as actual parameters) Arithmetic Operators:

More information

Chapter 1 Getting Started

Chapter 1 Getting Started Chapter 1 Getting Started The C# class Just like all object oriented programming languages, C# supports the concept of a class. A class is a little like a data structure in that it aggregates different

More information

Thread Safety. Review. Today o Confinement o Threadsafe datatypes Required reading. Concurrency Wrapper Collections

Thread Safety. Review. Today o Confinement o Threadsafe datatypes Required reading. Concurrency Wrapper Collections Thread Safety Today o Confinement o Threadsafe datatypes Required reading Concurrency Wrapper Collections Optional reading The material in this lecture and the next lecture is inspired by an excellent

More information

CS180 Review. Recitation Week 15

CS180 Review. Recitation Week 15 CS180 Review Recitation Week 15 Announcement Final exam will be held on Thursday(12/17) 8:00~10:00 AM The coverage is comprehensive Project 5 is graded. Check your score in Blackboard. Classes and Methods

More information

CMSC 330: Organization of Programming Languages

CMSC 330: Organization of Programming Languages CMSC 330: Organization of Programming Languages Multithreading Multiprocessors Description Multiple processing units (multiprocessor) From single microprocessor to large compute clusters Can perform multiple

More information

Answer Key. 1. General Understanding (10 points) think before you decide.

Answer Key. 1. General Understanding (10 points) think before you decide. Answer Key 1. General Understanding (10 points) Answer the following questions with yes or no. think before you decide. Read the questions carefully and (a) (2 points) Does the interface java.util.sortedset

More information

CS108, Stanford Handout #33. Sockets

CS108, Stanford Handout #33. Sockets CS108, Stanford Handout #33 Fall, 2008-09 Osvaldo Jiménez Sockets Thanks to Nick Parlante for much of this handout Sockets Sockets make network connections between machines, but you just read/write/block

More information

PRINCIPLES OF SOFTWARE BIM209DESIGN AND DEVELOPMENT 10. PUTTING IT ALL TOGETHER. Are we there yet?

PRINCIPLES OF SOFTWARE BIM209DESIGN AND DEVELOPMENT 10. PUTTING IT ALL TOGETHER. Are we there yet? PRINCIPLES OF SOFTWARE BIM209DESIGN AND DEVELOPMENT 10. PUTTING IT ALL TOGETHER Are we there yet? Developing software, OOA&D style You ve got a lot of new tools, techniques, and ideas about how to develop

More information

COMP 202 Java in one week

COMP 202 Java in one week COMP 202 Java in one week... Continued CONTENTS: Return to material from previous lecture At-home programming exercises Please Do Ask Questions It's perfectly normal not to understand everything Most of

More information

COMP31212: Concurrency A Review of Java Concurrency. Giles Reger

COMP31212: Concurrency A Review of Java Concurrency. Giles Reger COMP31212: Concurrency A Review of Java Concurrency Giles Reger Outline What are Java Threads? In Java, concurrency is achieved by Threads A Java Thread object is just an object on the heap, like any other

More information

1 OBJECT-ORIENTED PROGRAMMING 1

1 OBJECT-ORIENTED PROGRAMMING 1 PREFACE xvii 1 OBJECT-ORIENTED PROGRAMMING 1 1.1 Object-Oriented and Procedural Programming 2 Top-Down Design and Procedural Programming, 3 Problems with Top-Down Design, 3 Classes and Objects, 4 Fields

More information

Definition: A thread is a single sequential flow of control within a program.

Definition: A thread is a single sequential flow of control within a program. What Is a Thread? All programmers are familiar with writing sequential programs. You've probably written a program that displays "Hello World!" or sorts a list of names or computes a list of prime numbers.

More information

Informatica 3. Marcello Restelli. Laurea in Ingegneria Informatica Politecnico di Milano 9/15/07 10/29/07

Informatica 3. Marcello Restelli. Laurea in Ingegneria Informatica Politecnico di Milano 9/15/07 10/29/07 Informatica 3 Marcello Restelli 9/15/07 10/29/07 Laurea in Ingegneria Informatica Politecnico di Milano Structuring the Computation Control flow can be obtained through control structure at instruction

More information

Input, Output and Exceptions. COMS W1007 Introduction to Computer Science. Christopher Conway 24 June 2003

Input, Output and Exceptions. COMS W1007 Introduction to Computer Science. Christopher Conway 24 June 2003 Input, Output and Exceptions COMS W1007 Introduction to Computer Science Christopher Conway 24 June 2003 Input vs. Output We define input and output from the perspective of the programmer. Input is data

More information

COP 3330 Final Exam Review

COP 3330 Final Exam Review COP 3330 Final Exam Review I. The Basics (Chapters 2, 5, 6) a. comments b. identifiers, reserved words c. white space d. compilers vs. interpreters e. syntax, semantics f. errors i. syntax ii. run-time

More information

Lecture 8: September 30

Lecture 8: September 30 CMPSCI 377 Operating Systems Fall 2013 Lecture 8: September 30 Lecturer: Prashant Shenoy Scribe: Armand Halbert 8.1 Semaphores A semaphore is a more generalized form of a lock that can be used to regulate

More information

Programming in Parallel COMP755

Programming in Parallel COMP755 Programming in Parallel COMP755 All games have morals; and the game of Snakes and Ladders captures, as no other activity can hope to do, the eternal truth that for every ladder you hope to climb, a snake

More information

Hi everyone. Starting this week I'm going to make a couple tweaks to how section is run. The first thing is that I'm going to go over all the slides

Hi everyone. Starting this week I'm going to make a couple tweaks to how section is run. The first thing is that I'm going to go over all the slides Hi everyone. Starting this week I'm going to make a couple tweaks to how section is run. The first thing is that I'm going to go over all the slides for both problems first, and let you guys code them

More information

What did we talk about last time? Course overview Policies Schedule

What did we talk about last time? Course overview Policies Schedule Week 1 - Wednesday What did we talk about last time? Course overview Policies Schedule The book talks about stuff that you know pretty well as Java programmers I just want to talk about a few issues

More information

CS108, Stanford Handout #22. Thread 3 GUI

CS108, Stanford Handout #22. Thread 3 GUI CS108, Stanford Handout #22 Winter, 2006-07 Nick Parlante Thread 3 GUI GUIs and Threading Problem: Swing vs. Threads How to integrate the Swing/GUI/drawing system with threads? Problem: The GUI system

More information

05. SINGLETON PATTERN. One of a Kind Objects

05. SINGLETON PATTERN. One of a Kind Objects BIM492 DESIGN PATTERNS 05. SINGLETON PATTERN One of a Kind Objects Developer: What use is that? Guru: There are many objects we only need one of: thread pools, caches, dialog boxes, objects that handle

More information

Topic 6: Exceptions. Exceptions are a Java mechanism for dealing with errors & unusual situations

Topic 6: Exceptions. Exceptions are a Java mechanism for dealing with errors & unusual situations Topic 6: Exceptions Exceptions are a Java mechanism for dealing with errors & unusual situations Goals: learn how to... think about different responses to errors write code that catches exceptions write

More information

Multi-threading in Java. Jeff HUANG

Multi-threading in Java. Jeff HUANG Multi-threading in Java Jeff HUANG Software Engineering Group @HKUST Do you use them? 2 Do u know their internals? 3 Let s see File DB How can they service so many clients simultaneously? l 4 Multi-threading

More information

CONTENTS. Chapter 1 Getting Started with Java SE 6 1. Chapter 2 Exploring Variables, Data Types, Operators and Arrays 13

CONTENTS. Chapter 1 Getting Started with Java SE 6 1. Chapter 2 Exploring Variables, Data Types, Operators and Arrays 13 CONTENTS Chapter 1 Getting Started with Java SE 6 1 Introduction of Java SE 6... 3 Desktop Improvements... 3 Core Improvements... 4 Getting and Installing Java... 5 A Simple Java Program... 10 Compiling

More information

COMP-202 Unit 9: Exceptions

COMP-202 Unit 9: Exceptions COMP-202 Unit 9: Exceptions Course Evaluations Please do these. -Fast to do -Used to improve course for future. (Winter 2011 had 6 assignments reduced to 4 based on feedback!) 2 Avoiding errors So far,

More information

Overview. CMSC 330: Organization of Programming Languages. Concurrency. Multiprocessors. Processes vs. Threads. Computation Abstractions

Overview. CMSC 330: Organization of Programming Languages. Concurrency. Multiprocessors. Processes vs. Threads. Computation Abstractions CMSC 330: Organization of Programming Languages Multithreaded Programming Patterns in Java CMSC 330 2 Multiprocessors Description Multiple processing units (multiprocessor) From single microprocessor to

More information

M257 Past Paper Oct 2008 Attempted Solution

M257 Past Paper Oct 2008 Attempted Solution M257 Past Paper Oct 2008 Attempted Solution Part 1 Question 1 A version of Java is a particular release of the language, which may be succeeded by subsequent updated versions at a later time. Some examples

More information

CS61B, Spring 2003 Discussion #17 Amir Kamil UC Berkeley 5/12/03

CS61B, Spring 2003 Discussion #17 Amir Kamil UC Berkeley 5/12/03 CS61B, Spring 2003 Discussion #17 Amir Kamil UC Berkeley 5/12/03 Topics: Threading, Synchronization 1 Threading Suppose we want to create an automated program that hacks into a server. Many encryption

More information

CSCI 200 Lab 2 Inheritance, Polymorphism & Data Streams

CSCI 200 Lab 2 Inheritance, Polymorphism & Data Streams CSCI 200 Lab 2 Inheritance, Polymorphism & Data Streams In this lab you will write a set of simple Java interfaces and classes that use inheritance and polymorphism. You will also write code that uses

More information

Certification In Java Language Course Course Content

Certification In Java Language Course Course Content Introduction Of Java * What Is Java? * How To Get Java * A First Java Program * Compiling And Interpreting Applications * The JDK Directory Structure Certification In Java Language Course Course Content

More information

CS 159: Parallel Processing

CS 159: Parallel Processing Outline: Concurrency using Java CS 159: Parallel Processing Spring 2007 Processes vs Threads Thread basics Synchronization Locks Examples Avoiding problems Immutable objects Atomic operations High"level

More information

Java Primer. CITS2200 Data Structures and Algorithms. Topic 2

Java Primer. CITS2200 Data Structures and Algorithms. Topic 2 CITS2200 Data Structures and Algorithms Topic 2 Java Primer Review of Java basics Primitive vs Reference Types Classes and Objects Class Hierarchies Interfaces Exceptions Reading: Lambert and Osborne,

More information

Concurrency & Parallelism. Threads, Concurrency, and Parallelism. Multicore Processors 11/7/17

Concurrency & Parallelism. Threads, Concurrency, and Parallelism. Multicore Processors 11/7/17 Concurrency & Parallelism So far, our programs have been sequential: they do one thing after another, one thing at a. Let s start writing programs that do more than one thing at at a. Threads, Concurrency,

More information

Lecture 35. Threads. Reading for next time: Big Java What is a Thread?

Lecture 35. Threads. Reading for next time: Big Java What is a Thread? Lecture 35 Threads Reading for next time: Big Java 21.4 What is a Thread? Imagine a Java program that is reading large files over the Internet from several different servers (or getting data from several

More information

1) Discuss the mutual exclusion mechanism that you choose as implemented in the chosen language and the associated basic syntax

1) Discuss the mutual exclusion mechanism that you choose as implemented in the chosen language and the associated basic syntax Lab report Project 3 Mihai Ene I have implemented the solution in Java. I have leveraged its threading mechanisms and concurrent API (i.e. concurrent package) in order to achieve the required functionality

More information

Chair of Software Engineering. Java and C# in Depth. Prof. Dr. Bertrand Meyer. Exercise Session 8. Nadia Polikarpova

Chair of Software Engineering. Java and C# in Depth. Prof. Dr. Bertrand Meyer. Exercise Session 8. Nadia Polikarpova Chair of Software Engineering Java and C# in Depth Prof. Dr. Bertrand Meyer Exercise Session 8 Nadia Polikarpova Quiz 1: What is printed? (Java) class MyTask implements Runnable { «Everything is ok! public

More information

Exceptions. References. Exceptions. Exceptional Conditions. CSE 413, Autumn 2005 Programming Languages

Exceptions. References. Exceptions. Exceptional Conditions. CSE 413, Autumn 2005 Programming Languages References Exceptions "Handling Errors with Exceptions", Java tutorial http://java.sun.com/docs/books/tutorial/essential/exceptions/index.html CSE 413, Autumn 2005 Programming Languages http://www.cs.washington.edu/education/courses/413/05au/

More information

Threads, Concurrency, and Parallelism

Threads, Concurrency, and Parallelism Threads, Concurrency, and Parallelism Lecture 24 CS2110 Spring 2017 Concurrency & Parallelism So far, our programs have been sequential: they do one thing after another, one thing at a time. Let s start

More information

COMP-202 Unit 9: Exceptions

COMP-202 Unit 9: Exceptions COMP-202 Unit 9: Exceptions Announcements - Assignment 4: due Monday April 16th - Assignment 4: tutorial - Final exam tutorial next week 2 Exceptions An exception is an object that describes an unusual

More information

CSC System Development with Java. Exception Handling. Department of Statistics and Computer Science. Budditha Hettige

CSC System Development with Java. Exception Handling. Department of Statistics and Computer Science. Budditha Hettige CSC 308 2.0 System Development with Java Exception Handling Department of Statistics and Computer Science 1 2 Errors Errors can be categorized as several ways; Syntax Errors Logical Errors Runtime Errors

More information

Previous lecture: threads G51PRG: Introduction to Programming Second semester Lecture 12 URL

Previous lecture: threads G51PRG: Introduction to Programming Second semester Lecture 12 URL Previous lecture: threads G51PRG: Introduction to Programming Second semester Lecture 12 What is a thread Why use multiple threads Issues and problems involved Java threads Natasha Alechina School of Computer

More information

Job Migration. Job Migration

Job Migration. Job Migration Job Migration The Job Migration subsystem must provide a mechanism for executable programs and data to be serialized and sent through the network to a remote node. At the remote node, the executable programs

More information

Core Java Contents. Duration: 25 Hours (1 Month)

Core Java Contents. Duration: 25 Hours (1 Month) Duration: 25 Hours (1 Month) Core Java Contents Java Introduction Java Versions Java Features Downloading and Installing Java Setup Java Environment Developing a Java Application at command prompt Java

More information

Hashing. Reading: L&C 17.1, 17.3 Eck Programming Course CL I

Hashing. Reading: L&C 17.1, 17.3 Eck Programming Course CL I Hashing Reading: L&C 17.1, 17.3 Eck 10.3 Defne hashing Objectives Discuss the problem of collisions in hash tables Examine Java's HashMap implementation of hashing Look at HashMap example Save serializable

More information

Parallel Programming Languages COMP360

Parallel Programming Languages COMP360 Parallel Programming Languages COMP360 The way the processor industry is going, is to add more and more cores, but nobody knows how to program those things. I mean, two, yeah; four, not really; eight,

More information

Java Basics 5 - Sockets. Manuel Oriol - May 4th, 2006

Java Basics 5 - Sockets. Manuel Oriol - May 4th, 2006 Java Basics 5 - Sockets Manuel Oriol - May 4th, 2006 Connected / Disconnected Modes Connected mode: path chosen and packets arrive all, in correct order (e.g. Phone) Disconnected mode: path not chosen

More information

Concurrent Programming

Concurrent Programming Concurrency Concurrent Programming A sequential program has a single thread of control. Its execution is called a process. A concurrent program has multiple threads of control. They may be executed as

More information

Administration. Exceptions. Leftovers. Agenda. When Things Go Wrong. Handling Errors. CS 99 Summer 2000 Michael Clarkson Lecture 11

Administration. Exceptions. Leftovers. Agenda. When Things Go Wrong. Handling Errors. CS 99 Summer 2000 Michael Clarkson Lecture 11 Administration Exceptions CS 99 Summer 2000 Michael Clarkson Lecture 11 Lab 10 due tomorrow No lab tomorrow Work on final projects Remaining office hours Rick: today 2-3 Michael: Thursday 10-noon, Monday

More information

Internet Technology 2/7/2013

Internet Technology 2/7/2013 Sample Client-Server Program Internet Technology 02r. Programming with Sockets Paul Krzyzanowski Rutgers University Spring 2013 To illustrate programming with TCP/IP sockets, we ll write a small client-server

More information

1.00 Lecture 30. Sending information to a Java program

1.00 Lecture 30. Sending information to a Java program 1.00 Lecture 30 Input/Output Introduction to Streams Reading for next time: Big Java 15.5-15.7 Sending information to a Java program So far: use a GUI limited to specific interaction with user sometimes

More information

CN208 Introduction to Computer Programming

CN208 Introduction to Computer Programming CN208 Introduction to Computer Programming Lecture #11 Streams (Continued) Pimarn Apipattanamontre Email: pimarn@pimarn.com 1 The Object Class The Object class is the direct or indirect superclass of every

More information

MITOCW watch?v=w_-sx4vr53m

MITOCW watch?v=w_-sx4vr53m MITOCW watch?v=w_-sx4vr53m The following content is provided under a Creative Commons license. Your support will help MIT OpenCourseWare continue to offer high-quality educational resources for free. To

More information

Application Development in JAVA. Data Types, Variable, Comments & Operators. Part I: Core Java (J2SE) Getting Started

Application Development in JAVA. Data Types, Variable, Comments & Operators. Part I: Core Java (J2SE) Getting Started Application Development in JAVA Duration Lecture: Specialization x Hours Core Java (J2SE) & Advance Java (J2EE) Detailed Module Part I: Core Java (J2SE) Getting Started What is Java all about? Features

More information