Methods and Anonymous Classes - Lecture Slides | CMSC 433, Study notes of Programming Languages

Material Type: Notes; Professor: Sussman; Class: PROG LANG TECH & PDGMS; Subject: Computer Science; University: University of Maryland; Term: Unknown 1989;

Typology: Study notes

Pre 2010

Uploaded on 02/13/2009

koofers-user-dao
koofers-user-dao šŸ‡ŗšŸ‡ø

5

(1)

10 documents

1 / 5

Toggle sidebar

This page cannot be seen from the preview

Don't miss anything!

bg1
CMSC 433, Alan Sussman, U. Maryland (via
Bill Pugh) 1
CMSC433, Spring 2002
Programming Language
Technology and Paradigms
Java Threads
Alan Sussman
February 19, 2002
CMCS 433, Spring 2002 -Alan Sussman 2
Administrivia
•Project 2 due next Wednesday, Feb. 27
–questions?
•Project 1 commentary
–should have 2 programs to comment on by now
•Next time
–postmortem of project 1
CMCS 433, Spring 2002 -Alan Sussman 3
Last time -Java
•Wrapper classes, String and StringBuffer
–String is immutable, StringBuffer isn’t
•Exceptions
–shouldn’t ignore Errors, sometimes OK to ignore
Exceptions
–Exceptions are objects, subclass of Exception
–must declare user-defined Exceptions that can be
thrown by a method (part of return type)
–finally block always executed
•Inner classes
–nested classes/interfaces –behave like static
method/instance variable
•can only access statics of enclosing class CMCS 433, Spring 2002 -Alan Sussman 4
Standard Inner Classes
•Defined like a class method/variable
•Each instance associated with an instance of the
outer class
•If class Ais outer class
–use A.this to get thisfor instance of outer class
•Can refer to all methods/variables of outer class
–transparently
•Can’t have any static methods/variables
CMCS 433, Spring 2002 -Alan Sussman 5
Example
public class FixedStack {
Object [] array;
int top = 0;
class MyEnum implements java.util.Enumerator {
int count = top;
public boolean hasMoreElements() { return count > 0; }
public Object nextElement() {
if (count == 0)
throw new NoSuchElementException(ā€œFixedStackā€);
return array[--count]; }
}
public java.util.Enumerator enumerateAll() {
return new MyEnum(); }
} CMCS 433, Spring 2002 -Alan Sussman 6
Method and Anonymous Classes
•Can refer to all methods/variables of outer class
•Can refer to finallocal variables
•Can’t have any static methods/variables
•Method classes defined like a method variable
•Anonymous classes defined in new expression
–new BaseClassOrInterface() { extensions }
pf3
pf4
pf5

Partial preview of the text

Download Methods and Anonymous Classes - Lecture Slides | CMSC 433 and more Study notes Programming Languages in PDF only on Docsity!

CMSC 433, Alan Sussman, U. Maryland (via

CMSC433, Spring 2002

Programming Language

Technology and Paradigms

Java Threads

Alan Sussman

February 19, 2002

CMCS 433, Spring 2002 - Alan Sussman 2

Administrivia

• Project 2 due next Wednesday, Feb. 27

  • questions?

• Project 1 commentary

  • should have 2 programs to comment on by now

• Next time

  • postmortem of project 1

CMCS 433, Spring 2002 - Alan Sussman 3

Last time - Java

  • Wrapper classes, String and StringBuffer
    • String is immutable, StringBuffer isn’t
  • Exceptions
    • shouldn’t ignore Errors, sometimes OK to ignore Exceptions
    • Exceptions are objects, subclass of Exception
    • must declare user-defined Exceptions that can be thrown by a method (part of return type)
    • finally block always executed
  • Inner classes
    • nested classes/interfaces – behave like static method/instance variable - can only access statics of enclosing class CMCS 433, Spring 2002 - Alan Sussman 4

Standard Inner Classes

  • Defined like a class method/variable
  • Each instance associated with an instance of the

outer class

  • If class A is outer class
    • use A.this to get this for instance of outer class
  • Can refer to all methods/variables of outer class
    • transparently
  • Can’t have any static methods/variables

CMCS 433, Spring 2002 - Alan Sussman 5

Example

public class FixedStack { Object [] array; int top = 0; class MyEnum implements java.util.Enumerator { int count = top; public boolean hasMoreElements() { return count > 0; } public Object nextElement() { if (count == 0) throw new NoSuchElementException(ā€œFixedStackā€); return array[--count]; } } public java.util.Enumerator enumerateAll() { return new MyEnum(); } } CMCS 433, Spring 2002 - Alan Sussman 6

Method and Anonymous Classes

  • Can refer to all methods/variables of outer class
  • Can refer to final local variables
  • Can’t have any static methods/variables
  • Method classes defined like a method variable
  • Anonymous classes defined in new expression
    • new BaseClassOrInterface() { extensions }

CMSC 433, Alan Sussman, U. Maryland (via

CMCS 433, Spring 2002 - Alan Sussman 7

Method class Example

public class FixedStack { Object [] array; int top = 0; public java.util.Enumerator enumerateOldestK(final int k) { class MyEnum implements java.util.Enumerator { int pos = 0; public boolean hasMoreElements () { return pos < k && pos < top; } public Object nextElement() { if (!hasMoreElements()) { throw new NoSuchElementException(ā€œFixedStackā€); return array[pos++]; } } return new MyEnum(); } } CMCS 433, Spring 2002 - Alan Sussman^8

Anonymous class Example

public class FixedStack { Object [] array; int top = 0; public java.util.Enumerator enumerateOldestK(final int k) { return new java.util.Enumerator() { int pos = 0; public boolean hasMoreElements() { return pos < k && pos < top; } public Object nextElement() { if (!hasMoreElements()) throw new NoSuchElementException(ā€œFixedStackā€); return array[pos++]; } } } }

CMCS 433, Spring 2002 - Alan Sussman 9

Important details

  • If class B is defined inside of class A
    • a synchronized method of B locks B.this , not A.this
    • may want to lock A.this for synchronization
    • can have many B ’s for each A
  • Can’t define constructor for anonymous inner

class

  • Inner classes are a compile-time transformation
    • separate class file generated for each inner class
    • have $’s in names

I/O and Utility Libraries

CMCS 433, Spring 2002 - Alan Sussman 11

I/O Classes

  • File
    • directories
      • if(f.isDirectory()) System.out.println(f.list());
    • interface FilenameFilter – allows selection of sublist
  • OutputStream – byte stream going out
  • Writer – character stream going out
  • InputStream – byte stream coming in
  • Reader – character stream coming in

CMCS 433, Spring 2002 - Alan Sussman 12

OutputStream - bytes

  • base types
    • ByteArrayOutputStream
    • FileOutputStream – goes to file
    • PipedOutputStream – goes to PipedInputStream
    • SocketOutputStream (not public) – goes to TCP socket
  • Filters – wrapped around an OutputStream
    • BufferedOutputStream
    • ObjectOutputStream (should implement FilterOutputStream ) – serialization of object graph

CMSC 433, Alan Sussman, U. Maryland (via

CMCS 433, Spring 2002 - Alan Sussman 19

Enumerations and Bitsets

• Enumeration

  • an interface
  • used in many places to return an enumeration
    • public boolean hasMoreElements()
    • public Object nextElement()

• BitSet

  • provides representation of a set as a bit vector
  • grows as needed (like HashMap)

CMCS 433, Spring 2002 - Alan Sussman 20

Collection Classes

• interface Collection

  • interface List
    • class Vector (and Stack )
    • class ArrayList
    • class LinkedList – doubly linked
  • interface Set
    • class HashSet
    • interface SortedSet
      • class TreeSet

CMCS 433, Spring 2002 - Alan Sussman 21

Other libraries

• java.lang.Math

  • abstract final class – only static members
  • includes constants e and Ļ€
  • includes static methods for trig, exponentiation,

min, max, …

• java.text

  • text formatting tools
    • class MessageFormat provides printf/scanf functionality
  • lots of facilities for internationalization

Multithreading and

Synchronization

CMCS 433, Spring 2002 - Alan Sussman 23

What is a thread?

  • It’s a program counter and a stack
  • All threads share the same memory space
    • take turns with the CPU, for a uni-processor
    • run concurrently, on a multiprocessor
  • Example: Web browser
    • one thread for I/O
    • one thread for each file being downloaded
    • one thread to render web page
  • Running thread might
    • yield, sleep, wait for I/O or notify , be pre-empted

CMCS 433, Spring 2002 - Alan Sussman 24

Writing Multi-threaded Code

  • Need to control which events can happen

simultaneously

  • e.g., update and display methods for a class
  • Usually only covered in OS/DB courses
  • so few programmers have lots of training
  • Can get inconsistent results or deadlock
  • problems often not easily reproduced
  • Easy to get multi-threading, without trying
  • Graphical User Interfaces (GUI’s)
  • Remote Method Invocation

CMSC 433, Alan Sussman, U. Maryland (via

CMCS 433, Spring 2002 - Alan Sussman 25

Extending class Thread

• Can build a thread class by extending

java.lang.Thread

• Must supply a public void run() method

• Start a thread by invoking the start()

method

• When a thread starts, executes run ()

• When run() returns, thread is finished/dead

CMCS 433, Spring 2002 - Alan Sussman 26

Simple thread methods

• void start()

• boolean isAlive()

• void setDaemon(boolean on)

  • if only daemon threads running, VM terminates

• void setPriority(int newPriority )

  • thread scheduler might respect priority

• void join() throws InterruptedException

  • waits for a thread to die/finish

CMCS 433, Spring 2002 - Alan Sussman 27

Simple static thread methods

• Apply to thread invoking the method

  • void yield()
  • void sleep(long milliseconds)

throws InterruptedException

  • Thread currentThread()