Java and embedded systems. aQute Copyright © 2002 All rights reserved About me Peter Kriens Work as...

Preview:

Citation preview

aQute Copyright © 2002 All rights reserved

Java and embedded systems

aQute Copyright © 2002 All rights reserved

About me

Peter Kriens Work as a consultant

(mainly for for ERICSSON) Finnasandsvagen 22 43933 Onsala, Sweden +46 705950899 Peter.Kriens@aQute.se

aQute Copyright © 2002 All rights reserved

The language

Simple key word based language with lots of curly braces

public class A { public void main( String args[] ) { System.out.println( “Hello world” ); }}

Close resemblance to C/C++ basic syntax Formally defined

aQute Copyright © 2002 All rights reserved

The Language: Names Class name derived from directory and file name

watch case sensitiveness on PC’s redundant

Class names are globally unique com.ericsson.bcm.BCM

packages/classes can be imported for convenience import com.ericsson.bcm.*; full name is real name

aQute Copyright © 2002 All rights reserved

The language: Access controls

Access control build into language public private protected default: package private deprecated

aQute Copyright © 2002 All rights reserved

The Language: Interfaces Interface new concept Instead of multiple inheritance Verified promise to the type system to implement

a method Decouples sender from receiver Slight (very slight) overhead in current

implementations Versioning problems

aQute Copyright © 2002 All rights reserved

Interfaces

Logclient

SimpleLog

IBMLog

MotorolaLog

implements

usesinterface

public interface Log { public void log(String s);}

public class SimpleLog { public void log(String s) { System.out.println( s ); }}

aQute Copyright © 2002 All rights reserved

Interfaces and message dispatch

an object IBMLog

public void log(String s) { System.out.println( s ); }

Log

log(String)

log(“yes”) invokeinterface

resolve name

lookup method

aQute Copyright © 2002 All rights reserved

The Language: Nested classes

Used for callbacks Expensive

> 500 bytes overhead per class More linking

Requires quirks like final variables Ugly syntax

aQute Copyright © 2002 All rights reserved

Anonymous classes

void foo( final int offset ) { window.addActionListener( new Action() { public void performAction() { _count+=offset; }}});

IBMLog

com/ibm/log/IBMLog.class

IBMLog$1com/ibm/log/IBMLog$1.class

aQute Copyright © 2002 All rights reserved

The Language: Object Oriented

Java is mainly OO int, float, char, byte, long are not objects

problematic with for example reflection A class is an object

aQute Copyright © 2002 All rights reserved

Threads Easy to create a new thread

Thread thread = new Thread() { public void run() { …. }};

Threadgroups Treat a group of threads as one Monitor life of threads

Expensive resource! Stack Scheduling

aQute Copyright © 2002 All rights reserved

Threads

Thread

Data areathe heap

Stack area

Thread

Stack area

Thread

Stack area

ThreadGroup

aQute Copyright © 2002 All rights reserved

Threads: Monitors

Synchronized keyword Each object has a monitor Difficult to understand for many people But powerful Wait gives up lock

aQute Copyright © 2002 All rights reserved

Monitors

void push(Object o) { synchronized( _vector ) { _vector.addElement( o ); if ( _vector.size() == 1 ) notifyAll();} }

Object pop() { synchronized( _vector ) { while ( _vector.size() == 0 ) wait(); Object o = _vector.elementAt(0); _vector.removeElementAt(0);} }

Queue

monitor aThread

aThread

waiting

in

out

synchronized

aQute Copyright © 2002 All rights reserved

Threads: killing them Threads cannot be killed due to locks! Use variable and close() to get rid of threads

class DNS implements Runnable { boolean _continue = true; ServerSocket _socket; public void run() { try { _server = new ServerSocket(53); while ( _continue ) { Socket socket = server.accept(); process(socket); } } catch( IOException e ) { Log.report(e); } } public void quit() throws IOException { _continue = false; server.close();

}}

aQute Copyright © 2002 All rights reserved

Garbage collection

Never delete an object! Java will clean up after you. When no more references exist, an object is

finalized Do not get too sloppy, careful programming

always pays in the end

aQute Copyright © 2002 All rights reserved

Finalization

Careful with static variables A static variable can keep a class alive

finalize Gets called just before an object is removed No guarantee in what context

Threads! Not as important as C++ destructor

aQute Copyright © 2002 All rights reserved

Exceptions

Extra flow of control call/return and call/exception

Checked exceptions for errors that cannot be prevented (environment): IO errors, Not found

Unchecked (programmer errors): Null pointers Errors (integrity): Link errors

aQute Copyright © 2002 All rights reserved

Exception hierarchy

Object

Throwable

Error Exception

RuntimeException

IOException

...Exception

NullPointerException

...Exception

VerifyError

...Error

checked!

unchecked

do not catch

aQute Copyright © 2002 All rights reserved

Exceptions

Exceptions very useful for life cycle management for reliable functions

Interfaces often forget to throw no Exceptions while they should complicates implementation

public interface Printer { void print( String s ) /* throws IOException */;}

aQute Copyright © 2002 All rights reserved

Exceptions: problems

Checked exceptions create tight coupling between layers Force implementors to catch exceptions No standard logging mechanisms

Absolutely fatal:

public void foo() { try { process(); } catch( Exception e ) {}}

aQute Copyright © 2002 All rights reserved

Reflection

Access an object untyped Methods, Fields, Constructors, inheritance and

interfaces No type safety Can significantly reduce code size

Method m= String.class.getDeclaredMethod( “size”, new Class[] {} );Integer i = (Integer) m.invoke( “abc”, new Object[] {} );

aQute Copyright © 2002 All rights reserved

Dynamic linking References are resolved in run time by name and

signature Pretty lenient

Addition of new variables/methods/signatures Removal of unused methods

Static initialization when first referenced static {

doSomething();}

Size/Performance hit

aQute Copyright © 2002 All rights reserved

Dynamic linking

Def.classConstants"foo""bar"

Methods1: invoke 2

Abc.classConstants"bar""kim"

Methods1: ...

aQute Copyright © 2002 All rights reserved

Class path

Hardest thing to get right ClassNotFoundException is dreaded

Exception could be on class A while class B referenced by A could not be found!

aClient A B

Use A, link in

refers to extends

also link in

reports A!!

aQute Copyright © 2002 All rights reserved

Classpath

Rules: Names are case sensitive even if file system is not Current directory is not default included in class path Use a make file to maintain class path Do not hard code paths to 3pp products everywhere

aQute Copyright © 2002 All rights reserved

Class loaders

Java abstracts where code comes from

aClient aClassLoader

links in class aFileretrieves byte codes

aClassanObjectbelongs to class

refers to

is loaded bydb, network, etc

aQute Copyright © 2002 All rights reserved

Class Loaders

Code can from anywhere network, database, file system calculation on the fly (new RMI, Voyager)

Class loader defines security scope Very simple to implement

aQute Copyright © 2002 All rights reserved

Class identity crisis

Two identical class loaded via two different class loaders are different classes!

aClient

BLoader

AClass

Aclassfile

ALoader

AClass

aObject bObjectThese objects are NOT of the same class

is loaded byis loaded by

bound to

aQute Copyright © 2002 All rights reserved

Type safety

Java is type safe by design String s = (String) new Integer() Does not compile, does not get past verifier Allows optimizations

However, an object can be cast to another class. Verified in run time Expensive

Type safety verified by byte code verifier

aQute Copyright © 2002 All rights reserved

Byte codes

A byte code is an instruction to a virtual machine. Compare with an op code for a real processor RETURN = 0xB1 SALOAD = 0x35

Byte codes generated by compiler or assembler The VM can directly interpret the byte codes A JIT is a Just In Time Compiler that translates

the byte codes to native op codes

aQute Copyright © 2002 All rights reserved

Byte codes

Disassemble code with javap javap -c -classpath /src ericsson.net.ipv4.IP

Local variables for method int dotted(java.lang.String) java.lang.String s pc=0, length=54, slot=0 java.util.StringTokenizer st pc=11, length=43, slot=1 int[] n pc=15, length=39, slot=2 int i pc=17, length=21, slot=3Method int dotted(int, int, int, int) 0 iload_0 1 bipush 24 3 ishl 4 iload_1 5 bipush 16 7 ishl 8 iadd 9 iload_2 10 bipush 8

aQute Copyright © 2002 All rights reserved

Class files A class file contains all the byte codes and linking

information for one class format version constant pool interfaces super class fields methods debug info

aQute Copyright © 2002 All rights reserved

Class files Contains always only 1 class

Nested classes are <name>$<n> No optimization for performance and size Long class names cause your class files to grow

exponentially! +/- 500 bytes overhead per class Class name = file path is confusing

Classpath problems are a serious problem in Java

aQute Copyright © 2002 All rights reserved

Jar Files Packs a number of class files in a compressed ZIP

file Faster downloading in HTTP 1.0 servers made a

connection for each class file Contains classes + resources

images web pages translations

Easier to ship

aQute Copyright © 2002 All rights reserved

Jar Files No optimization or pre linking

Plain zip file Java support for parsing/extracting JAR files

Example content jar tvf ericsson*.jar

31 Mon Nov 22 12:21:42 CET 1999 ericsson/net/ipv4/resources.txt 1572 Mon Nov 22 12:21:44 CET 1999 ericsson/net/ipv4/UDP.class 2759 Mon Nov 22 12:21:44 CET 1999 ericsson/net/ipv4/TCP.class 1441 Mon Nov 22 12:21:44 CET 1999 ericsson/net/ipv4/ICMP.class 32 Mon Nov 22 12:21:44 CET 1999 ericsson/rcur/btest/resources.txt 3486 Mon Nov 22 12:21:44 CET 1999 ericsson/rcur/btest/Lme.class 11401 Mon Nov 22 12:21:44 CET 1999 ericsson/net/ipv4/IP.class 2481 Mon Nov 22 12:21:44 CET 1999 ericsson/net/ipv4/Network.class

aQute Copyright © 2002 All rights reserved

Jar Files: Manifest Manifest

Signing of files for security Options: main class, package versions

Manifest-Version: 1.0Created-By: Signtool (signtool 1.1)Comments: PLEASE DO NOT EDIT THIS FILE. YOU WILL BREAK IT.

Name: java/awt/Adjustable.classSHA1-Digest: 181v4ECne8mD6ZqcHP3JVD6l17k=

Name: java/awt/AWTError.classSHA1-Digest: /ekvoK3hUnQ+amWPopPc2iujHMU=

Name: java/awt/AWTEvent.classSHA1-Digest: Jm/yZUSuRs7yZX2IGGVIG4ULD/M=

aQute Copyright © 2002 All rights reserved

Performance

Class loading overhead. Native code is mapped to memory and paged in.

Class linking overhead. Linking is symbolic Two VM’s do not share byte codes in memory

Modern OS'es share executable memory images

VM-1 VM-2

Class files

aQute Copyright © 2002 All rights reserved

Performance

Interpretation or poor optimization when JIT is used

No dirty tricks: C: char c[100]; int x = (int) *c; Java: byte c[] = new byte[100]; int x =((0xFF&c[0])<<24) +

((0xFF&c[1])<<16) + ((0xFF&c[2])<<8) + (0xFF&c[3]);

No pre-processor distinction between develop/release difficult

aQute Copyright © 2002 All rights reserved

Security

Classes are authorized by their “codebase”. The class loader defines the security scope

Privilege is minimum privilege of all callers on the stack

Significant change from Java 1.1 SecurityManager to Java 2 AccessController

aQute Copyright © 2002 All rights reserved

Security

anA

aB

aC

A

B

C

Openfile

CCBBBA

ProtectionDomain

CodeSource

PermissionCollection Permissions Permission

FilePermissions

FilePermission

SecurityManager

AccessController

stack

foo()

bar()

open()

checkRead(File)check(FilePermission)

get stack traceuse minimal permission

Check permission

implies(FilePermission)

implies(FilePermission)

implies(FilePermission)

Policy

aQute Copyright © 2002 All rights reserved

Security Java 2

Each class loader has a protection domain A protection domain holds a collection of

Permission object. Permission objects have a target and actions

FilePermission /tmp/- + read,write, execute, delete

SocketPermission people.ericsson.se:80 + accept, connect, listen, resolve

aQute Copyright © 2002 All rights reserved

Java Profiles

Java 2 Enterprise Edition Java 2 Standard Edition Java 2 Micro Edition

CDC = Standard VM CLDC = KVM

Migration Personal Java Java Card

aQute Copyright © 2002 All rights reserved

User Interfaces: AWT

AWT, original UI library Poor event handling Uses peer objects

Native look & feel (when you are lucky) Impossible to get right on all platforms

Client TextComponent

PeerTextField

aQute Copyright © 2002 All rights reserved

User Interfaces: Swing

UI library fully implemented in Java

Big ….. and slow Uses many, many classes

> 16 Button related classes Pluggable UI >700 classes loaded for "Hello world"

Surprisingly easy to use and good looking

aQute Copyright © 2002 All rights reserved

User Interfaces: IFC (Netscape) Same concept as Swing

same designers! No more maintenance by Netscape

no bug fixes (wonderful stability) source code available

Has UI builder called Constructor Small, lean

Whole library < 400K jar file embedded in Netscape

aQute Copyright © 2002 All rights reserved

Java versus C++

No more stray pointer related core dumps Useful exceptions No more memory leaks Cleaner, simpler syntax Less performance Better productivity

aQute Copyright © 2002 All rights reserved

Open Service Gateway initiative

ERICSSON, SUN, IBM, Telia, Nokia, Toshiba, Nortel, Siemens, EDF, …

Standardize the Java API for applications residing on the residential gateway

Serviceprovider Aggregator OSGi

e-boxServiceprovider

OSGie-box

OSGie-box

ClientsPC, video,...

aQute Copyright © 2002 All rights reserved

OSGi

Framework Life cycle management (install,start,stop, update,

uninstall) Registry

Http server Logging Client access Remote Admin

aQute Copyright © 2002 All rights reserved

Why did Java get so big?

Politics, APIs included that should not have been in the base CORBA Swing

Design method Analysis models confused with design models Peanut sized classes: Swing ‘Hello world’ loads 700

classes ...

aQute Copyright © 2002 All rights reserved

Why did Java get so big?

Requirement for perfection API’s must cover all cases perfectly (though they

rarely do) Lack of ‘dirty’ optimization tricks Design by committee Lack of time?

aQute Copyright © 2002 All rights reserved

Optimizing Threads are expensive Design with sense

just enough classes Use reflection Minimize short lived objects Use tools to build JAR file

JAX (see alphaworks) Deliver (ericsson Utility)

aQute Copyright © 2002 All rights reserved

Conclusion Java clearly improves productivity over C++ Performance and size are issues Libraries available for any thinkable subject

Not always well designed The de-facto language of today

It is not Smalltalk, but it is usually fun to work with …

aQute Copyright © 2002 All rights reserved

References

Java: www.javasoft.com Java Developers Connection:

http://developer.java.sun.com OSGi: www.osgi.org JPadPro (simple IDE):

http://www.modelworks.com/products.html

aQute Copyright © 2002 All rights reserved

References

JProbe: http://www.klgroup.com/jprobe/profiler/index.html

IBM source code: alphaworks.ibm.com Voyager: www.objectspace.com PSE Pro: www.odi.com Links to java related:

http://www.taxon.demon.nl/JW

aQute Copyright © 2002 All rights reserved

Java Books

Java in a Nutshell David Flanagan. ISBN 1-56592-183-6

Java Secrets Elliote Rusty Harold.ISBN 0-7645-8007-8

Java 2 Performance and idiom guide Craig Larman, Rhett Guthrie. ISBN 0-13-014260-3

aQute Copyright © 2002 All rights reserved

Java Books The Java Virtual Machine Specification

Tim Lindholm, Frank Yellin, ISBN 0-201-63452-X Java Security

Scott Oaks. ISBN 1-56592-403-7 Java Developers Almanac

Patrick Chan. ISBN 0-201-37967-8 Late night IFC

Jason Beaver, Jamie Costa, Jason Wehling. ISBN 1-56276-540-X

Recommended