SlideShare a Scribd company logo
Intro to Java
for ECS 160

Stoney Jackson
jacksoni@cs.ucdavis.edu
wwwcsif.cs.ucdavis.edu/~jacksoni

What’s the first question you’ve got to
ask about a language named Java?
Can you make coffee with it?

2
It was meant to!!
A programming language for appliances!

3
Must Run on Any Architecture
debug

“WRITE ONCE, RUN ANYWHERE!”
Program
in Java

Java
Compiler

Java Virtual Machine

pretty portable

Java
Bytecode

Java Virtual Machine

4
Doesn’t Make Coffee Yet

5
So What’s Java Good For?
Web applications!

Java Applet
Java Applet

Server

6
Java on the Web: Java Applets



Clients download applets via Web browser
Browser runs applet in a Java Virtual Machine
(JVM)
Applet

Client

Server

Interactive web, security, and client consistency
Slow to download, inconsistent VMs (besides,
flash won this war)
7
Java on the Web: J2EE



Thin clients (minimize download)
Java all “server side”
JSPs
Servlets

Client

Server
EJB

THIS IS WHAT YOU’LL BE DOING!!

JDBC

8
The Java programming environment


Compared to C++:










Object-orientation: Classes + Inheritance
Distributed: RMI, Servlet, Distributed object programming.
Robust: Strong typing + no pointer + garbage collection
Secure: Type-safety + access control
Architecture neutral: architecture neutral representation
Portable
Interpreted




no header files, macros, pointers and references, unions,
operator overloading, templates, etc.

High performance through Just in time compilation +
runtime modification of code

Multi-threaded

9
Java Features


Well defined primitive data types: int, float, double, char,
etc.


int 4 bytes [–2,147,648, 2,147,483,647]



Control statements similar to C++: if-then-else, switch,
while, for



Interfaces



Exceptions



Concurrency



Packages



Name spaces



Reflection



Applet model

10
The Java programming environment


Java programming language specification
Syntax of Java programs
 Defines different constructs and their semantics














Java byte code: Intermediate representation for Java
programs
Java compiler: Transform Java programs into Java byte
code
Java interpreter: Read programs written in Java byte code
and execute them
Java virtual machine: Runtime system that provides
various services to running programs
Java programming environment: Set of libraries that
provide services such as GUI, data structures,etc.
Java enabled browsers: Browsers that include a JVM +
ability to load programs from remote hosts

11
Java: A tiny intro


How are Java programs written?



How are variables declared?



How are expressions specified?



How are control structures defined?



How to define simple methods?



What are classes and objects?



What about exceptions?

12
How are Java programs written?


Define a class HelloWorld and store it into a file:
HelloWorld.java:
public class HelloWorld {
public static void main (String[] args) {
System.out.println(“Hello, World”);
}
}



Compile HelloWorld.java
javac HelloWorld.java

Output: HelloWorld.class


Run
java HelloWorld

Output: Hello, World

13
How are variables declared?
Fibonacci:
class Fibonacci {
public static void main(String[] arg) {
int lo = 1;
int hi = 1;
System.out.println(lo);
while (hi < 50) {
System.out.println(hi);
hi = lo + hi;
lo = hi – lo;
}
}
}

14
How to define expressions?


Arithmetic: +, -, *,/, %, =
8 + 3 * 2 /4
Use standard precedence and associativity rules



Predicates: ==, !=, >, <, >=, <=
public class Demo {
public static void main (String[] argv) {
boolean b;
b = (2 + 2 == 4);
System.out.println(b);

}

}

15
How are simple methods defined?
Every method is defined inside a Java class definition
public class Movie {
public static int movieRating(int s, int a, int d) {
return s+a+d;

}

}
public class Demo {
public static void main (String argv[]) {
int script = 6, acting = 9, directing = 8;
displayRating(script, acting, directing);

}
public static void displayRating(int s, int a, int d){
System.out.print(“The rating of this movie is”);
System.out.println(Movie.movieRating(s, a, d));

}

}

16
How are control structures specified?
Typical flow of control statements: if-then-else, while, switch,
do-while, and blocks
class ImprovedFibo {
static final int MAX_INDEX = 10;
public static void main (String[] args) {
int lo = 1;
int hi = 1;
String mark = null;
for (int i = 2; i < MAX_INDEX; i++) {
if ((i % 2) == 0)
mark = " *";
else mark = "";
System.out.println(i+ ": " + hi + mark);
hi = lo + hi;
lo = hi - lo;
}}}

17
What are classes and objects?
Classes: templates for constructing instances
 Fields
Instance variables
 Static variables




Methods
Instance
 Static


class Point {
public double x, y;
}
Point lowerleft = new Point();
Point upperRight = new Point();
Point middlePoint = new Point();
lowerLeft.x = 0.0; lowerLeft.y = 0.0;
upperRight.x = 1280.0; upperRight.y = 1024.0
middlePoint.x = 640.0; middlePoint.y = 512.0

18
How are instance methods defined?
Instance methods take an implicit parameter:
instance on which method is invoked
public class Movie {
public int script, acting, directing;
public int rating() {
return script + acting + directing;

}

}
public class Demo {
public static void main (String argv[]) {
Movie m = new Movie();
m.script = 6; m.acting = 9; m.directing = 8;
System.out.print(“The rating of this movie is”);
System.out.println(m.rating());

}

}

19
How to extend classes?




Inheritance: mechanism for extending behavior
of classes; leads to construction of hierarchy of
classes [Note: no multiple inheritance]
What happens when class C extends class D:






Inherits
Inherits
Inherits
Inherits
C can:





instance variables
static variables
instance methods
static methods

Add new instance variables
Add new methods (static and dynamic)
Modify methods (only implementation)
Cannot delete anything

20
How to extend classes?
public class Attraction {
public int minutes;
public Attraction() {minutes = 75;}
public int getMinutes() {return minutes;}
public void setMinutes(int d) {minutes = d;}
}
public class Movie extends Attraction {
public int script, acting, directing;
public Movie() {script = 5; acting = 5; directing = 5;}
public Movie(int s, int a, int d) {
script = s; acting = a; directing = d;
}
public int rating() {return script + acting + directing;}
}
public class Symphony extends Attraction {
public int playing, music, conducting;
public Symphony() {playing = music = conducting = 5;}
public Symphony(int p, int m, int c) {
playing = p; music = m; conducting = c;
}
public int rating() {return playing + music + conducting;}
}

21
What are abstract classes?


Abstract class: Merely a place holder for class
definitions; cannot be used to create instances.;
public abstract class Attraction {
public int minutes;
public Attraction() {minutes = 75;}
public int getMinutes() {return minutes;}
public void setMinutes(int d) {minutes = d;}
public abstract void m();
}



Following is an error:

Attraction x;
x = new Attraction();



Following is not an error:
public class Movie extends Attraction { … }
public class Symphony extends Attraction { … }
Attraction x;
x = new Movie ();
x = new Symphony();

22
Packages
Object
extends
Attraction

Auxiliaries

Demonstration

extends
Movie

Symphony

• How do we organize above classes into a single unit? Put them in file?
However, only one public class per file (whose name is same as file’s)
• Solution: Place several files (compilation units) into a package

23
Packages – cont’d.




units of organizing related Classes, Interfaces,
Sub packages
Why?





Java programs typically organized in terms of
packages and subpackages





Reduce name clashing
Limit visibility of names

Each package may then be divided into several
packages, subpackages, and classes
Each class can then be stored in a separate file

Each source file starts with something like:
package mypackage;


Code in source file is now part of mypackage

24
Packages – cont’d.
package onto.java.entertainment;
public abstract class Attraction { … }

package onto.java.entertainment;
public class Movie extends class Attraction {…}

package onto.java.entertainment;
import java.io.*;
import java.util.*;
public class Auxiliaries { … }

•Where to store packages?
•How does Java find packages?
•Export and Import
•Access control

25
Exceptions
public class A {
public void foo() throws MyException {
if(aBadThingHappened()) {
throw new MyException();
}
}
public void bar() {
try {
this.foo();
} catch (MyException e) {
e.printStackTrace();
}
}
}
public class MyException extends Exception {
public MyException() {}
public MyException(String message) {
super(String message);
}
}

26
Finally
public class A {
public void foo() throws MyException {
throw new MyException();
}
}
public void bar() {
try {
this.foo();
} catch (MyException e) {
e.printStackTrace();
} catch (YourException e) {
e.printStackTrace();
} finally {
... // always executed before leaving the try/catch
}
}
}

27
Resources


http://java.sun.com/


Java[tm] 2 Platform, Standard Edition v1.4.1






java, javac, jar, jre, etc.
Any platform... FREE!

Online documentation and tutorials

http://www.eclipse.org/
Integrated development environment (IDE) for nothing in
particular
 Java[tm] development tools (JDT) (comes with Eclips)







Project management
Editor
Incremental compiler
CVS support

C/C++ extension in progress
 AspectJ support
 Windows, Linux, and Mac.... FREE!


28
Qualifiers







public – any class* may access
(no qualifier) “package protected” – only the
class* and classes* in the same package may
access
protected – only the class* and decendent
classes* may access
private – only the class* may access


The class or instances of the class (an object of the
class)

29
Package Protected
package edu.ucdavis;
public class A {
int x;
}
package edu.ucdavis;
public class B {
void foo(A a) { a.x; } // OK, same package
}
package org.omg;
public class B {
void foo(A a) { a.x; } // Not OK, different package
}
package edu.ucdavis.cs;
public class B {
void foo(A a) { a.x; } // Not OK, different package
}
package edu.ucdavis.cs;
public class B {
void foo(A a) { a.x; } // Not OK, different package
}
package edu;
public class B {
void foo(A a) { a.x; } // Not OK, different package
}

30
Protected
public class A {
protected int x;
}
public class B extends A {
void foo(A a) { this.x; a.x; } // OK, B is a decendent of A
}
public class C extends B {
void foo(A a) { this.x; a.x; } // OK, C is a decendent of A through
B
}
package edu; // Uh oh!
public class D extends C {
void foo(A a) { this.x; a.x; } // OK, D is a decendent of A
}
public class E {
void foo(A a) { this.x; a.x; } // NOT OK, E is NOT a decendent of A
}

31
Threads






Multiple “threads” of execution within the same
program, share the same memory space ->
“lightweight”.
Perform multiple tasks at the same time.
Work on the same task in parallel.
Heavily used in user interfaces.






Web browsers: load web pages while the user can still
scroll, go back, open a new window, etc.
Web servers: serve multiple requests in parallel.

Can take advantage of multiple processors.
Threads in Java



Java manages and schedules threads
Java provides “synchronize” to help coordinate multiple
threads

32
Creating a Thread in Java
public class MyThread extends Thread {
public MyThread(String threadName) {
super(threadName);
}
public void run() {
for(int i = 0; i < 10; i++) {
System.out.println(i + “ “ + getName());
try {
sleep((long)(Math.random() * 1000));
} catch(InterruptedException e) {}
}
}
}

33
Creating a Thread in Java
public class ThreadTest {
public static void main(String[] args) {
for(int i = 0; i < args.length; i++) {
MyThread t = new MyThread(args[i]);
t.start();
}
}
}
> java ThreadTest Bob Frank
0 Bob
0 Frank
1 Bob
2 Bob
1 Frank
3 Bob
2 Frank
3 Frank
4 Frank
...

34
Creating a Thread in Java via Interface
public class MyRunnable implements
String name;
public MyRunnable(String name) {
this.name = name;
}
public void run() {
for(int i; i < 10; i++) {
System.out.println(i + “ “ +
try {
sleep((long)(Math.random()
} catch(InterruptedException
}
}
}

Runnable {

name());
* 1000));
e) {}

public class ThreadTest {
public static void main(String[] args) {
for(int i = 0; i < args.length; i++) {
Thread t = new Thread(new MyRunnable(args[i]), args[i]);
t.start();
}
}
}

35
Producer Consumer Problem
public class Producer
extends Thread {
private Share shared;

public class Consumer
extends Thread {
private Share shared;

public Producer(Share s) {
shared = s;
}

public Consumer(Share s) {
shared = s;
}

public void run() {
for(int i = 0; i < 10; i++){
shared.put(i);
}
}

public void run() {
int value;
for(int i = 0; i < 10; i++) {
value = shared.get();
}
}

}
}
shared.put(0)
shared.get() // 0 gotten
shared.get() // 0 gotten again!!
shared.put(0)
shared.put(1)
shared.get() // 0 never gotten!!

// what about simultaneous
// access?!
shared.put(0) shared.get()
RACE CONDITIONS!

36
Synchronized
public class Share {
private int s;
public synchronized int get() { ... }
public synchronized void put(int s) { ... }
}

Synchronized provides mutual exclusion on an
object
 For any object, only one thread may execute
inside any of that object’s synchronized
Share s1 = new Share();
t1 -> s1.get() // gets in
methods
Share s2 = new Share();
t2 -> s1.put(32) // blocks


Thread t1 = ...;
Thread t2 = ...;

t1 -> s1.get() // gets in
t2 -> s2.put(4) // gets in

37
Producer Consumer Coordination
public class Share {
private int s;
private boolean empty = true;

}

public synchronized int get() {
while (empty == true) {
try {
wait(); // nothing to get, wait
} catch (InterruptedException e) {}
}
empty = true;
notifyAll(); // wakeup waiting Consumers/Producers
return s;
}
public synchronized void put(int s) {
while (empty == false) {
try {
wait(); // no room
} catch (InterruptedException e) {}
}
this.s = s;
empty = false;
notifyAll(); // wakeup waiting Consumers/Producers
}

38

More Related Content

What's hot

Web Security - Hands-on
Web Security - Hands-onWeb Security - Hands-on
Web Security - Hands-on
Andrea Valenza
 
Making Java more dynamic: runtime code generation for the JVM
Making Java more dynamic: runtime code generation for the JVMMaking Java more dynamic: runtime code generation for the JVM
Making Java more dynamic: runtime code generation for the JVM
Rafael Winterhalter
 
Getting started with Java 9 modules
Getting started with Java 9 modulesGetting started with Java 9 modules
Getting started with Java 9 modules
Rafael Winterhalter
 
Java Tutorial
Java Tutorial Java Tutorial
Java Tutorial
Akash Pandey
 
C# 6.0 Introduction
C# 6.0 IntroductionC# 6.0 Introduction
C# 6.0 Introduction
Olav Haugen
 
Java Tutorial | My Heart
Java Tutorial | My HeartJava Tutorial | My Heart
Java Tutorial | My Heart
Bui Kiet
 
Mastering Java Bytecode With ASM - 33rd degree, 2012
Mastering Java Bytecode With ASM - 33rd degree, 2012Mastering Java Bytecode With ASM - 33rd degree, 2012
Mastering Java Bytecode With ASM - 33rd degree, 2012Anton Arhipov
 
Hello Java-First Level
Hello Java-First LevelHello Java-First Level
Hello Java-First Level
Dr. Raaid Alubady
 
Hello java
Hello java  Hello java
Kotlin Language Features - A Java comparison
Kotlin Language Features - A Java comparisonKotlin Language Features - A Java comparison
Kotlin Language Features - A Java comparison
Ed Austin
 
Java 104
Java 104Java 104
Java 104
Manuela Grindei
 
SOLID Ruby SOLID Rails
SOLID Ruby SOLID RailsSOLID Ruby SOLID Rails
SOLID Ruby SOLID Rails
Michael Mahlberg
 
Java tut1 Coderdojo Cahersiveen
Java tut1 Coderdojo CahersiveenJava tut1 Coderdojo Cahersiveen
Java tut1 Coderdojo Cahersiveen
Graham Royce
 
Java tut1
Java tut1Java tut1
Java tut1
Ajmal Khan
 
Tutorial java
Tutorial javaTutorial java
Tutorial java
Abdul Aziz
 
Java 10, Java 11 and beyond
Java 10, Java 11 and beyondJava 10, Java 11 and beyond
Java 10, Java 11 and beyond
Rafael Winterhalter
 
Basic java for Android Developer
Basic java for Android DeveloperBasic java for Android Developer
Basic java for Android Developer
Nattapong Tonprasert
 
Lecture 6, c++(complete reference,herbet sheidt)chapter-16
Lecture 6, c++(complete reference,herbet sheidt)chapter-16Lecture 6, c++(complete reference,herbet sheidt)chapter-16
Lecture 6, c++(complete reference,herbet sheidt)chapter-16
Abu Saleh
 

What's hot (20)

Web Security - Hands-on
Web Security - Hands-onWeb Security - Hands-on
Web Security - Hands-on
 
Making Java more dynamic: runtime code generation for the JVM
Making Java more dynamic: runtime code generation for the JVMMaking Java more dynamic: runtime code generation for the JVM
Making Java more dynamic: runtime code generation for the JVM
 
Getting started with Java 9 modules
Getting started with Java 9 modulesGetting started with Java 9 modules
Getting started with Java 9 modules
 
Java Tutorial
Java Tutorial Java Tutorial
Java Tutorial
 
C# 6.0 Introduction
C# 6.0 IntroductionC# 6.0 Introduction
C# 6.0 Introduction
 
Java Tutorial | My Heart
Java Tutorial | My HeartJava Tutorial | My Heart
Java Tutorial | My Heart
 
Mastering Java Bytecode With ASM - 33rd degree, 2012
Mastering Java Bytecode With ASM - 33rd degree, 2012Mastering Java Bytecode With ASM - 33rd degree, 2012
Mastering Java Bytecode With ASM - 33rd degree, 2012
 
Java 5 and 6 New Features
Java 5 and 6 New FeaturesJava 5 and 6 New Features
Java 5 and 6 New Features
 
Hello Java-First Level
Hello Java-First LevelHello Java-First Level
Hello Java-First Level
 
Hello java
Hello java  Hello java
Hello java
 
Kotlin Language Features - A Java comparison
Kotlin Language Features - A Java comparisonKotlin Language Features - A Java comparison
Kotlin Language Features - A Java comparison
 
Java 104
Java 104Java 104
Java 104
 
SOLID Ruby SOLID Rails
SOLID Ruby SOLID RailsSOLID Ruby SOLID Rails
SOLID Ruby SOLID Rails
 
Java tut1 Coderdojo Cahersiveen
Java tut1 Coderdojo CahersiveenJava tut1 Coderdojo Cahersiveen
Java tut1 Coderdojo Cahersiveen
 
Java tut1
Java tut1Java tut1
Java tut1
 
Tutorial java
Tutorial javaTutorial java
Tutorial java
 
Java 10, Java 11 and beyond
Java 10, Java 11 and beyondJava 10, Java 11 and beyond
Java 10, Java 11 and beyond
 
Basic java for Android Developer
Basic java for Android DeveloperBasic java for Android Developer
Basic java for Android Developer
 
Lecture 6, c++(complete reference,herbet sheidt)chapter-16
Lecture 6, c++(complete reference,herbet sheidt)chapter-16Lecture 6, c++(complete reference,herbet sheidt)chapter-16
Lecture 6, c++(complete reference,herbet sheidt)chapter-16
 
Java 7 New Features
Java 7 New FeaturesJava 7 New Features
Java 7 New Features
 

Viewers also liked

Writing your own DSL
Writing your own DSLWriting your own DSL
Writing your own DSL
Rob Kinyon
 
Creative platforms
Creative platformsCreative platforms
Creative platformstshawmedia
 
Vagrant
VagrantVagrant
Vagrant
Rob Kinyon
 
Ruby, the language of devops
Ruby, the language of devopsRuby, the language of devops
Ruby, the language of devops
Rob Kinyon
 
Scuba Diving Equipment List
Scuba Diving Equipment ListScuba Diving Equipment List
Scuba Diving Equipment List
Sher Thapa
 

Viewers also liked (12)

Writing your own DSL
Writing your own DSLWriting your own DSL
Writing your own DSL
 
Java
JavaJava
Java
 
Creative platforms
Creative platformsCreative platforms
Creative platforms
 
Introduction to matlab
Introduction to matlabIntroduction to matlab
Introduction to matlab
 
Vishal kashyap
Vishal kashyapVishal kashyap
Vishal kashyap
 
Java
JavaJava
Java
 
Java tutorials
Java tutorialsJava tutorials
Java tutorials
 
Uml for Java Programmers
Uml for Java ProgrammersUml for Java Programmers
Uml for Java Programmers
 
Vagrant
VagrantVagrant
Vagrant
 
Java applets
Java appletsJava applets
Java applets
 
Ruby, the language of devops
Ruby, the language of devopsRuby, the language of devops
Ruby, the language of devops
 
Scuba Diving Equipment List
Scuba Diving Equipment ListScuba Diving Equipment List
Scuba Diving Equipment List
 

Similar to Introduction to-java

Java Programs Lab File
Java Programs Lab FileJava Programs Lab File
Java Programs Lab File
Kandarp Tiwari
 
Implementation of interface9 cm604.30
Implementation of interface9 cm604.30Implementation of interface9 cm604.30
Implementation of interface9 cm604.30myrajendra
 
Java ppt Gandhi Ravi (gandhiri@gmail.com)
Java ppt  Gandhi Ravi  (gandhiri@gmail.com)Java ppt  Gandhi Ravi  (gandhiri@gmail.com)
Java ppt Gandhi Ravi (gandhiri@gmail.com)
Gandhi Ravi
 
Introduction to Software Development
Introduction to Software DevelopmentIntroduction to Software Development
Introduction to Software Development
Zeeshan MIrza
 
Object-oriented Basics
Object-oriented BasicsObject-oriented Basics
Object-oriented Basics
Jamie (Taka) Wang
 
JavaProgrammingForBeginners-Presentation.pdf
JavaProgrammingForBeginners-Presentation.pdfJavaProgrammingForBeginners-Presentation.pdf
JavaProgrammingForBeginners-Presentation.pdf
Sathwika7
 
JVM Mechanics: When Does the JVM JIT & Deoptimize?
JVM Mechanics: When Does the JVM JIT & Deoptimize?JVM Mechanics: When Does the JVM JIT & Deoptimize?
JVM Mechanics: When Does the JVM JIT & Deoptimize?
Doug Hawkins
 
E:\Plp 2009 2\Plp 9
E:\Plp 2009 2\Plp 9E:\Plp 2009 2\Plp 9
E:\Plp 2009 2\Plp 9
Ismar Silveira
 
Paradigmas de linguagens de programacao - aula#9
Paradigmas de linguagens de programacao - aula#9Paradigmas de linguagens de programacao - aula#9
Paradigmas de linguagens de programacao - aula#9
Ismar Silveira
 
Eric Lafortune - The Jack and Jill build system
Eric Lafortune - The Jack and Jill build systemEric Lafortune - The Jack and Jill build system
Eric Lafortune - The Jack and Jill build system
GuardSquare
 
SystemVerilog OOP Ovm Features Summary
SystemVerilog OOP Ovm Features SummarySystemVerilog OOP Ovm Features Summary
SystemVerilog OOP Ovm Features Summary
Amal Khailtash
 
Java Basics
Java BasicsJava Basics
Java Basics
Sunil OS
 
00_Introduction to Java.ppt
00_Introduction to Java.ppt00_Introduction to Java.ppt
00_Introduction to Java.ppt
HongAnhNguyn285885
 
Java Notes by C. Sreedhar, GPREC
Java Notes by C. Sreedhar, GPRECJava Notes by C. Sreedhar, GPREC
Java Notes by C. Sreedhar, GPREC
Sreedhar Chowdam
 
Java Notes
Java Notes Java Notes
Java Notes
Sreedhar Chowdam
 
05. Java Loops Methods and Classes
05. Java Loops Methods and Classes05. Java Loops Methods and Classes
05. Java Loops Methods and Classes
Intro C# Book
 

Similar to Introduction to-java (20)

1- java
1- java1- java
1- java
 
Java Programs Lab File
Java Programs Lab FileJava Programs Lab File
Java Programs Lab File
 
Implementation of interface9 cm604.30
Implementation of interface9 cm604.30Implementation of interface9 cm604.30
Implementation of interface9 cm604.30
 
Javalecture 1
Javalecture 1Javalecture 1
Javalecture 1
 
Java ppt Gandhi Ravi (gandhiri@gmail.com)
Java ppt  Gandhi Ravi  (gandhiri@gmail.com)Java ppt  Gandhi Ravi  (gandhiri@gmail.com)
Java ppt Gandhi Ravi (gandhiri@gmail.com)
 
Introduction to Software Development
Introduction to Software DevelopmentIntroduction to Software Development
Introduction to Software Development
 
Object-oriented Basics
Object-oriented BasicsObject-oriented Basics
Object-oriented Basics
 
JavaProgrammingForBeginners-Presentation.pdf
JavaProgrammingForBeginners-Presentation.pdfJavaProgrammingForBeginners-Presentation.pdf
JavaProgrammingForBeginners-Presentation.pdf
 
JVM Mechanics: When Does the JVM JIT & Deoptimize?
JVM Mechanics: When Does the JVM JIT & Deoptimize?JVM Mechanics: When Does the JVM JIT & Deoptimize?
JVM Mechanics: When Does the JVM JIT & Deoptimize?
 
Need 4 Speed FI
Need 4 Speed FINeed 4 Speed FI
Need 4 Speed FI
 
E:\Plp 2009 2\Plp 9
E:\Plp 2009 2\Plp 9E:\Plp 2009 2\Plp 9
E:\Plp 2009 2\Plp 9
 
Paradigmas de linguagens de programacao - aula#9
Paradigmas de linguagens de programacao - aula#9Paradigmas de linguagens de programacao - aula#9
Paradigmas de linguagens de programacao - aula#9
 
Eric Lafortune - The Jack and Jill build system
Eric Lafortune - The Jack and Jill build systemEric Lafortune - The Jack and Jill build system
Eric Lafortune - The Jack and Jill build system
 
SystemVerilog OOP Ovm Features Summary
SystemVerilog OOP Ovm Features SummarySystemVerilog OOP Ovm Features Summary
SystemVerilog OOP Ovm Features Summary
 
Java Basics
Java BasicsJava Basics
Java Basics
 
00_Introduction to Java.ppt
00_Introduction to Java.ppt00_Introduction to Java.ppt
00_Introduction to Java.ppt
 
Java Notes by C. Sreedhar, GPREC
Java Notes by C. Sreedhar, GPRECJava Notes by C. Sreedhar, GPREC
Java Notes by C. Sreedhar, GPREC
 
Java Notes
Java Notes Java Notes
Java Notes
 
05. Java Loops Methods and Classes
05. Java Loops Methods and Classes05. Java Loops Methods and Classes
05. Java Loops Methods and Classes
 
Java
JavaJava
Java
 

Recently uploaded

A Strategic Approach: GenAI in Education
A Strategic Approach: GenAI in EducationA Strategic Approach: GenAI in Education
A Strategic Approach: GenAI in Education
Peter Windle
 
Model Attribute Check Company Auto Property
Model Attribute  Check Company Auto PropertyModel Attribute  Check Company Auto Property
Model Attribute Check Company Auto Property
Celine George
 
The approach at University of Liverpool.pptx
The approach at University of Liverpool.pptxThe approach at University of Liverpool.pptx
The approach at University of Liverpool.pptx
Jisc
 
Guidance_and_Counselling.pdf B.Ed. 4th Semester
Guidance_and_Counselling.pdf B.Ed. 4th SemesterGuidance_and_Counselling.pdf B.Ed. 4th Semester
Guidance_and_Counselling.pdf B.Ed. 4th Semester
Atul Kumar Singh
 
Thesis Statement for students diagnonsed withADHD.ppt
Thesis Statement for students diagnonsed withADHD.pptThesis Statement for students diagnonsed withADHD.ppt
Thesis Statement for students diagnonsed withADHD.ppt
EverAndrsGuerraGuerr
 
Introduction to AI for Nonprofits with Tapp Network
Introduction to AI for Nonprofits with Tapp NetworkIntroduction to AI for Nonprofits with Tapp Network
Introduction to AI for Nonprofits with Tapp Network
TechSoup
 
June 3, 2024 Anti-Semitism Letter Sent to MIT President Kornbluth and MIT Cor...
June 3, 2024 Anti-Semitism Letter Sent to MIT President Kornbluth and MIT Cor...June 3, 2024 Anti-Semitism Letter Sent to MIT President Kornbluth and MIT Cor...
June 3, 2024 Anti-Semitism Letter Sent to MIT President Kornbluth and MIT Cor...
Levi Shapiro
 
2024.06.01 Introducing a competency framework for languag learning materials ...
2024.06.01 Introducing a competency framework for languag learning materials ...2024.06.01 Introducing a competency framework for languag learning materials ...
2024.06.01 Introducing a competency framework for languag learning materials ...
Sandy Millin
 
1.4 modern child centered education - mahatma gandhi-2.pptx
1.4 modern child centered education - mahatma gandhi-2.pptx1.4 modern child centered education - mahatma gandhi-2.pptx
1.4 modern child centered education - mahatma gandhi-2.pptx
JosvitaDsouza2
 
Palestine last event orientationfvgnh .pptx
Palestine last event orientationfvgnh .pptxPalestine last event orientationfvgnh .pptx
Palestine last event orientationfvgnh .pptx
RaedMohamed3
 
Honest Reviews of Tim Han LMA Course Program.pptx
Honest Reviews of Tim Han LMA Course Program.pptxHonest Reviews of Tim Han LMA Course Program.pptx
Honest Reviews of Tim Han LMA Course Program.pptx
timhan337
 
Instructions for Submissions thorugh G- Classroom.pptx
Instructions for Submissions thorugh G- Classroom.pptxInstructions for Submissions thorugh G- Classroom.pptx
Instructions for Submissions thorugh G- Classroom.pptx
Jheel Barad
 
BÀI TẬP BỔ TRỢ TIẾNG ANH GLOBAL SUCCESS LỚP 3 - CẢ NĂM (CÓ FILE NGHE VÀ ĐÁP Á...
BÀI TẬP BỔ TRỢ TIẾNG ANH GLOBAL SUCCESS LỚP 3 - CẢ NĂM (CÓ FILE NGHE VÀ ĐÁP Á...BÀI TẬP BỔ TRỢ TIẾNG ANH GLOBAL SUCCESS LỚP 3 - CẢ NĂM (CÓ FILE NGHE VÀ ĐÁP Á...
BÀI TẬP BỔ TRỢ TIẾNG ANH GLOBAL SUCCESS LỚP 3 - CẢ NĂM (CÓ FILE NGHE VÀ ĐÁP Á...
Nguyen Thanh Tu Collection
 
Unit 2- Research Aptitude (UGC NET Paper I).pdf
Unit 2- Research Aptitude (UGC NET Paper I).pdfUnit 2- Research Aptitude (UGC NET Paper I).pdf
Unit 2- Research Aptitude (UGC NET Paper I).pdf
Thiyagu K
 
Sha'Carri Richardson Presentation 202345
Sha'Carri Richardson Presentation 202345Sha'Carri Richardson Presentation 202345
Sha'Carri Richardson Presentation 202345
beazzy04
 
The French Revolution Class 9 Study Material pdf free download
The French Revolution Class 9 Study Material pdf free downloadThe French Revolution Class 9 Study Material pdf free download
The French Revolution Class 9 Study Material pdf free download
Vivekanand Anglo Vedic Academy
 
Additional Benefits for Employee Website.pdf
Additional Benefits for Employee Website.pdfAdditional Benefits for Employee Website.pdf
Additional Benefits for Employee Website.pdf
joachimlavalley1
 
TESDA TM1 REVIEWER FOR NATIONAL ASSESSMENT WRITTEN AND ORAL QUESTIONS WITH A...
TESDA TM1 REVIEWER  FOR NATIONAL ASSESSMENT WRITTEN AND ORAL QUESTIONS WITH A...TESDA TM1 REVIEWER  FOR NATIONAL ASSESSMENT WRITTEN AND ORAL QUESTIONS WITH A...
TESDA TM1 REVIEWER FOR NATIONAL ASSESSMENT WRITTEN AND ORAL QUESTIONS WITH A...
EugeneSaldivar
 
CACJapan - GROUP Presentation 1- Wk 4.pdf
CACJapan - GROUP Presentation 1- Wk 4.pdfCACJapan - GROUP Presentation 1- Wk 4.pdf
CACJapan - GROUP Presentation 1- Wk 4.pdf
camakaiclarkmusic
 
Unit 8 - Information and Communication Technology (Paper I).pdf
Unit 8 - Information and Communication Technology (Paper I).pdfUnit 8 - Information and Communication Technology (Paper I).pdf
Unit 8 - Information and Communication Technology (Paper I).pdf
Thiyagu K
 

Recently uploaded (20)

A Strategic Approach: GenAI in Education
A Strategic Approach: GenAI in EducationA Strategic Approach: GenAI in Education
A Strategic Approach: GenAI in Education
 
Model Attribute Check Company Auto Property
Model Attribute  Check Company Auto PropertyModel Attribute  Check Company Auto Property
Model Attribute Check Company Auto Property
 
The approach at University of Liverpool.pptx
The approach at University of Liverpool.pptxThe approach at University of Liverpool.pptx
The approach at University of Liverpool.pptx
 
Guidance_and_Counselling.pdf B.Ed. 4th Semester
Guidance_and_Counselling.pdf B.Ed. 4th SemesterGuidance_and_Counselling.pdf B.Ed. 4th Semester
Guidance_and_Counselling.pdf B.Ed. 4th Semester
 
Thesis Statement for students diagnonsed withADHD.ppt
Thesis Statement for students diagnonsed withADHD.pptThesis Statement for students diagnonsed withADHD.ppt
Thesis Statement for students diagnonsed withADHD.ppt
 
Introduction to AI for Nonprofits with Tapp Network
Introduction to AI for Nonprofits with Tapp NetworkIntroduction to AI for Nonprofits with Tapp Network
Introduction to AI for Nonprofits with Tapp Network
 
June 3, 2024 Anti-Semitism Letter Sent to MIT President Kornbluth and MIT Cor...
June 3, 2024 Anti-Semitism Letter Sent to MIT President Kornbluth and MIT Cor...June 3, 2024 Anti-Semitism Letter Sent to MIT President Kornbluth and MIT Cor...
June 3, 2024 Anti-Semitism Letter Sent to MIT President Kornbluth and MIT Cor...
 
2024.06.01 Introducing a competency framework for languag learning materials ...
2024.06.01 Introducing a competency framework for languag learning materials ...2024.06.01 Introducing a competency framework for languag learning materials ...
2024.06.01 Introducing a competency framework for languag learning materials ...
 
1.4 modern child centered education - mahatma gandhi-2.pptx
1.4 modern child centered education - mahatma gandhi-2.pptx1.4 modern child centered education - mahatma gandhi-2.pptx
1.4 modern child centered education - mahatma gandhi-2.pptx
 
Palestine last event orientationfvgnh .pptx
Palestine last event orientationfvgnh .pptxPalestine last event orientationfvgnh .pptx
Palestine last event orientationfvgnh .pptx
 
Honest Reviews of Tim Han LMA Course Program.pptx
Honest Reviews of Tim Han LMA Course Program.pptxHonest Reviews of Tim Han LMA Course Program.pptx
Honest Reviews of Tim Han LMA Course Program.pptx
 
Instructions for Submissions thorugh G- Classroom.pptx
Instructions for Submissions thorugh G- Classroom.pptxInstructions for Submissions thorugh G- Classroom.pptx
Instructions for Submissions thorugh G- Classroom.pptx
 
BÀI TẬP BỔ TRỢ TIẾNG ANH GLOBAL SUCCESS LỚP 3 - CẢ NĂM (CÓ FILE NGHE VÀ ĐÁP Á...
BÀI TẬP BỔ TRỢ TIẾNG ANH GLOBAL SUCCESS LỚP 3 - CẢ NĂM (CÓ FILE NGHE VÀ ĐÁP Á...BÀI TẬP BỔ TRỢ TIẾNG ANH GLOBAL SUCCESS LỚP 3 - CẢ NĂM (CÓ FILE NGHE VÀ ĐÁP Á...
BÀI TẬP BỔ TRỢ TIẾNG ANH GLOBAL SUCCESS LỚP 3 - CẢ NĂM (CÓ FILE NGHE VÀ ĐÁP Á...
 
Unit 2- Research Aptitude (UGC NET Paper I).pdf
Unit 2- Research Aptitude (UGC NET Paper I).pdfUnit 2- Research Aptitude (UGC NET Paper I).pdf
Unit 2- Research Aptitude (UGC NET Paper I).pdf
 
Sha'Carri Richardson Presentation 202345
Sha'Carri Richardson Presentation 202345Sha'Carri Richardson Presentation 202345
Sha'Carri Richardson Presentation 202345
 
The French Revolution Class 9 Study Material pdf free download
The French Revolution Class 9 Study Material pdf free downloadThe French Revolution Class 9 Study Material pdf free download
The French Revolution Class 9 Study Material pdf free download
 
Additional Benefits for Employee Website.pdf
Additional Benefits for Employee Website.pdfAdditional Benefits for Employee Website.pdf
Additional Benefits for Employee Website.pdf
 
TESDA TM1 REVIEWER FOR NATIONAL ASSESSMENT WRITTEN AND ORAL QUESTIONS WITH A...
TESDA TM1 REVIEWER  FOR NATIONAL ASSESSMENT WRITTEN AND ORAL QUESTIONS WITH A...TESDA TM1 REVIEWER  FOR NATIONAL ASSESSMENT WRITTEN AND ORAL QUESTIONS WITH A...
TESDA TM1 REVIEWER FOR NATIONAL ASSESSMENT WRITTEN AND ORAL QUESTIONS WITH A...
 
CACJapan - GROUP Presentation 1- Wk 4.pdf
CACJapan - GROUP Presentation 1- Wk 4.pdfCACJapan - GROUP Presentation 1- Wk 4.pdf
CACJapan - GROUP Presentation 1- Wk 4.pdf
 
Unit 8 - Information and Communication Technology (Paper I).pdf
Unit 8 - Information and Communication Technology (Paper I).pdfUnit 8 - Information and Communication Technology (Paper I).pdf
Unit 8 - Information and Communication Technology (Paper I).pdf
 

Introduction to-java

  • 1. Intro to Java for ECS 160 Stoney Jackson jacksoni@cs.ucdavis.edu wwwcsif.cs.ucdavis.edu/~jacksoni What’s the first question you’ve got to ask about a language named Java?
  • 2. Can you make coffee with it? 2
  • 3. It was meant to!! A programming language for appliances! 3
  • 4. Must Run on Any Architecture debug “WRITE ONCE, RUN ANYWHERE!” Program in Java Java Compiler Java Virtual Machine pretty portable Java Bytecode Java Virtual Machine 4
  • 6. So What’s Java Good For? Web applications! Java Applet Java Applet Server 6
  • 7. Java on the Web: Java Applets   Clients download applets via Web browser Browser runs applet in a Java Virtual Machine (JVM) Applet Client Server Interactive web, security, and client consistency Slow to download, inconsistent VMs (besides, flash won this war) 7
  • 8. Java on the Web: J2EE   Thin clients (minimize download) Java all “server side” JSPs Servlets Client Server EJB THIS IS WHAT YOU’LL BE DOING!! JDBC 8
  • 9. The Java programming environment  Compared to C++:         Object-orientation: Classes + Inheritance Distributed: RMI, Servlet, Distributed object programming. Robust: Strong typing + no pointer + garbage collection Secure: Type-safety + access control Architecture neutral: architecture neutral representation Portable Interpreted   no header files, macros, pointers and references, unions, operator overloading, templates, etc. High performance through Just in time compilation + runtime modification of code Multi-threaded 9
  • 10. Java Features  Well defined primitive data types: int, float, double, char, etc.  int 4 bytes [–2,147,648, 2,147,483,647]  Control statements similar to C++: if-then-else, switch, while, for  Interfaces  Exceptions  Concurrency  Packages  Name spaces  Reflection  Applet model 10
  • 11. The Java programming environment  Java programming language specification Syntax of Java programs  Defines different constructs and their semantics        Java byte code: Intermediate representation for Java programs Java compiler: Transform Java programs into Java byte code Java interpreter: Read programs written in Java byte code and execute them Java virtual machine: Runtime system that provides various services to running programs Java programming environment: Set of libraries that provide services such as GUI, data structures,etc. Java enabled browsers: Browsers that include a JVM + ability to load programs from remote hosts 11
  • 12. Java: A tiny intro  How are Java programs written?  How are variables declared?  How are expressions specified?  How are control structures defined?  How to define simple methods?  What are classes and objects?  What about exceptions? 12
  • 13. How are Java programs written?  Define a class HelloWorld and store it into a file: HelloWorld.java: public class HelloWorld { public static void main (String[] args) { System.out.println(“Hello, World”); } }  Compile HelloWorld.java javac HelloWorld.java Output: HelloWorld.class  Run java HelloWorld Output: Hello, World 13
  • 14. How are variables declared? Fibonacci: class Fibonacci { public static void main(String[] arg) { int lo = 1; int hi = 1; System.out.println(lo); while (hi < 50) { System.out.println(hi); hi = lo + hi; lo = hi – lo; } } } 14
  • 15. How to define expressions?  Arithmetic: +, -, *,/, %, = 8 + 3 * 2 /4 Use standard precedence and associativity rules  Predicates: ==, !=, >, <, >=, <= public class Demo { public static void main (String[] argv) { boolean b; b = (2 + 2 == 4); System.out.println(b); } } 15
  • 16. How are simple methods defined? Every method is defined inside a Java class definition public class Movie { public static int movieRating(int s, int a, int d) { return s+a+d; } } public class Demo { public static void main (String argv[]) { int script = 6, acting = 9, directing = 8; displayRating(script, acting, directing); } public static void displayRating(int s, int a, int d){ System.out.print(“The rating of this movie is”); System.out.println(Movie.movieRating(s, a, d)); } } 16
  • 17. How are control structures specified? Typical flow of control statements: if-then-else, while, switch, do-while, and blocks class ImprovedFibo { static final int MAX_INDEX = 10; public static void main (String[] args) { int lo = 1; int hi = 1; String mark = null; for (int i = 2; i < MAX_INDEX; i++) { if ((i % 2) == 0) mark = " *"; else mark = ""; System.out.println(i+ ": " + hi + mark); hi = lo + hi; lo = hi - lo; }}} 17
  • 18. What are classes and objects? Classes: templates for constructing instances  Fields Instance variables  Static variables   Methods Instance  Static  class Point { public double x, y; } Point lowerleft = new Point(); Point upperRight = new Point(); Point middlePoint = new Point(); lowerLeft.x = 0.0; lowerLeft.y = 0.0; upperRight.x = 1280.0; upperRight.y = 1024.0 middlePoint.x = 640.0; middlePoint.y = 512.0 18
  • 19. How are instance methods defined? Instance methods take an implicit parameter: instance on which method is invoked public class Movie { public int script, acting, directing; public int rating() { return script + acting + directing; } } public class Demo { public static void main (String argv[]) { Movie m = new Movie(); m.script = 6; m.acting = 9; m.directing = 8; System.out.print(“The rating of this movie is”); System.out.println(m.rating()); } } 19
  • 20. How to extend classes?   Inheritance: mechanism for extending behavior of classes; leads to construction of hierarchy of classes [Note: no multiple inheritance] What happens when class C extends class D:      Inherits Inherits Inherits Inherits C can:     instance variables static variables instance methods static methods Add new instance variables Add new methods (static and dynamic) Modify methods (only implementation) Cannot delete anything 20
  • 21. How to extend classes? public class Attraction { public int minutes; public Attraction() {minutes = 75;} public int getMinutes() {return minutes;} public void setMinutes(int d) {minutes = d;} } public class Movie extends Attraction { public int script, acting, directing; public Movie() {script = 5; acting = 5; directing = 5;} public Movie(int s, int a, int d) { script = s; acting = a; directing = d; } public int rating() {return script + acting + directing;} } public class Symphony extends Attraction { public int playing, music, conducting; public Symphony() {playing = music = conducting = 5;} public Symphony(int p, int m, int c) { playing = p; music = m; conducting = c; } public int rating() {return playing + music + conducting;} } 21
  • 22. What are abstract classes?  Abstract class: Merely a place holder for class definitions; cannot be used to create instances.; public abstract class Attraction { public int minutes; public Attraction() {minutes = 75;} public int getMinutes() {return minutes;} public void setMinutes(int d) {minutes = d;} public abstract void m(); }  Following is an error: Attraction x; x = new Attraction();  Following is not an error: public class Movie extends Attraction { … } public class Symphony extends Attraction { … } Attraction x; x = new Movie (); x = new Symphony(); 22
  • 23. Packages Object extends Attraction Auxiliaries Demonstration extends Movie Symphony • How do we organize above classes into a single unit? Put them in file? However, only one public class per file (whose name is same as file’s) • Solution: Place several files (compilation units) into a package 23
  • 24. Packages – cont’d.   units of organizing related Classes, Interfaces, Sub packages Why?    Java programs typically organized in terms of packages and subpackages    Reduce name clashing Limit visibility of names Each package may then be divided into several packages, subpackages, and classes Each class can then be stored in a separate file Each source file starts with something like: package mypackage;  Code in source file is now part of mypackage 24
  • 25. Packages – cont’d. package onto.java.entertainment; public abstract class Attraction { … } package onto.java.entertainment; public class Movie extends class Attraction {…} package onto.java.entertainment; import java.io.*; import java.util.*; public class Auxiliaries { … } •Where to store packages? •How does Java find packages? •Export and Import •Access control 25
  • 26. Exceptions public class A { public void foo() throws MyException { if(aBadThingHappened()) { throw new MyException(); } } public void bar() { try { this.foo(); } catch (MyException e) { e.printStackTrace(); } } } public class MyException extends Exception { public MyException() {} public MyException(String message) { super(String message); } } 26
  • 27. Finally public class A { public void foo() throws MyException { throw new MyException(); } } public void bar() { try { this.foo(); } catch (MyException e) { e.printStackTrace(); } catch (YourException e) { e.printStackTrace(); } finally { ... // always executed before leaving the try/catch } } } 27
  • 28. Resources  http://java.sun.com/  Java[tm] 2 Platform, Standard Edition v1.4.1     java, javac, jar, jre, etc. Any platform... FREE! Online documentation and tutorials http://www.eclipse.org/ Integrated development environment (IDE) for nothing in particular  Java[tm] development tools (JDT) (comes with Eclips)      Project management Editor Incremental compiler CVS support C/C++ extension in progress  AspectJ support  Windows, Linux, and Mac.... FREE!  28
  • 29. Qualifiers     public – any class* may access (no qualifier) “package protected” – only the class* and classes* in the same package may access protected – only the class* and decendent classes* may access private – only the class* may access  The class or instances of the class (an object of the class) 29
  • 30. Package Protected package edu.ucdavis; public class A { int x; } package edu.ucdavis; public class B { void foo(A a) { a.x; } // OK, same package } package org.omg; public class B { void foo(A a) { a.x; } // Not OK, different package } package edu.ucdavis.cs; public class B { void foo(A a) { a.x; } // Not OK, different package } package edu.ucdavis.cs; public class B { void foo(A a) { a.x; } // Not OK, different package } package edu; public class B { void foo(A a) { a.x; } // Not OK, different package } 30
  • 31. Protected public class A { protected int x; } public class B extends A { void foo(A a) { this.x; a.x; } // OK, B is a decendent of A } public class C extends B { void foo(A a) { this.x; a.x; } // OK, C is a decendent of A through B } package edu; // Uh oh! public class D extends C { void foo(A a) { this.x; a.x; } // OK, D is a decendent of A } public class E { void foo(A a) { this.x; a.x; } // NOT OK, E is NOT a decendent of A } 31
  • 32. Threads     Multiple “threads” of execution within the same program, share the same memory space -> “lightweight”. Perform multiple tasks at the same time. Work on the same task in parallel. Heavily used in user interfaces.     Web browsers: load web pages while the user can still scroll, go back, open a new window, etc. Web servers: serve multiple requests in parallel. Can take advantage of multiple processors. Threads in Java   Java manages and schedules threads Java provides “synchronize” to help coordinate multiple threads 32
  • 33. Creating a Thread in Java public class MyThread extends Thread { public MyThread(String threadName) { super(threadName); } public void run() { for(int i = 0; i < 10; i++) { System.out.println(i + “ “ + getName()); try { sleep((long)(Math.random() * 1000)); } catch(InterruptedException e) {} } } } 33
  • 34. Creating a Thread in Java public class ThreadTest { public static void main(String[] args) { for(int i = 0; i < args.length; i++) { MyThread t = new MyThread(args[i]); t.start(); } } } > java ThreadTest Bob Frank 0 Bob 0 Frank 1 Bob 2 Bob 1 Frank 3 Bob 2 Frank 3 Frank 4 Frank ... 34
  • 35. Creating a Thread in Java via Interface public class MyRunnable implements String name; public MyRunnable(String name) { this.name = name; } public void run() { for(int i; i < 10; i++) { System.out.println(i + “ “ + try { sleep((long)(Math.random() } catch(InterruptedException } } } Runnable { name()); * 1000)); e) {} public class ThreadTest { public static void main(String[] args) { for(int i = 0; i < args.length; i++) { Thread t = new Thread(new MyRunnable(args[i]), args[i]); t.start(); } } } 35
  • 36. Producer Consumer Problem public class Producer extends Thread { private Share shared; public class Consumer extends Thread { private Share shared; public Producer(Share s) { shared = s; } public Consumer(Share s) { shared = s; } public void run() { for(int i = 0; i < 10; i++){ shared.put(i); } } public void run() { int value; for(int i = 0; i < 10; i++) { value = shared.get(); } } } } shared.put(0) shared.get() // 0 gotten shared.get() // 0 gotten again!! shared.put(0) shared.put(1) shared.get() // 0 never gotten!! // what about simultaneous // access?! shared.put(0) shared.get() RACE CONDITIONS! 36
  • 37. Synchronized public class Share { private int s; public synchronized int get() { ... } public synchronized void put(int s) { ... } } Synchronized provides mutual exclusion on an object  For any object, only one thread may execute inside any of that object’s synchronized Share s1 = new Share(); t1 -> s1.get() // gets in methods Share s2 = new Share(); t2 -> s1.put(32) // blocks  Thread t1 = ...; Thread t2 = ...; t1 -> s1.get() // gets in t2 -> s2.put(4) // gets in 37
  • 38. Producer Consumer Coordination public class Share { private int s; private boolean empty = true; } public synchronized int get() { while (empty == true) { try { wait(); // nothing to get, wait } catch (InterruptedException e) {} } empty = true; notifyAll(); // wakeup waiting Consumers/Producers return s; } public synchronized void put(int s) { while (empty == false) { try { wait(); // no room } catch (InterruptedException e) {} } this.s = s; empty = false; notifyAll(); // wakeup waiting Consumers/Producers } 38