Download presentation
Presentation is loading. Please wait.
Published byRiley Duncan Modified over 10 years ago
1
Java and embedded systems
2
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
3
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
4
aQute Copyright © 2002 All rights reserved The Language: Names Class name derived from directory and file name watch case sensitiveness on PCs 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
5
aQute Copyright © 2002 All rights reserved The language: Access controls Access control build into language public private protected default: package private deprecated
6
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
7
aQute Copyright © 2002 All rights reserved Interfaces Log client Simple Log IBM Log Motorola Log implements uses interface public interface Log { public void log(String s); } public class SimpleLog { public void log(String s) { System.out.println( s ); } }
8
aQute Copyright © 2002 All rights reserved Interfaces and message dispatch an object IBM Log public void log(String s) { System.out.println( s ); } Log log(String) log(yes)invokeinterface resolve name lookup method
9
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
10
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$1 com/ibm/log/IBMLog$1.class
11
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
12
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
13
aQute Copyright © 2002 All rights reserved Threads Thread Data area the heap Stack area Thread Stack area Thread Stack area Thread Group
14
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
15
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 waiting in out synchronized
16
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(); }}
17
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
18
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
19
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
20
aQute Copyright © 2002 All rights reserved Exception hierarchy Object Throwable ErrorException Runtime Exception IO Exception... Exception NullPointer Exception... Exception Verify Error... Error checked! unchecked do not catch
21
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 */; }
22
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 ) {} }
23
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[] {} );
24
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
25
aQute Copyright © 2002 All rights reserved Dynamic linking Def.class Constants "foo" "bar" Methods 1: invoke 2 Abc.class Constants "bar" "kim" Methods 1:...
26
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! aClientAB Use A, link in refers toextends also link in reports A!!
27
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
28
aQute Copyright © 2002 All rights reserved Class loaders Java abstracts where code comes from aClient aClass Loader links in class aFile retrieves byte codes aClassanObject belongs to class refers to is loaded by db, network, etc
29
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
30
aQute Copyright © 2002 All rights reserved Class identity crisis Two identical class loaded via two different class loaders are different classes! aClient B Loader AClass Aclass file A Loader AClass aObjectbObject These objects are NOT of the same class is loaded by bound to
31
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
32
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
33
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=3 Method 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
34
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
35
aQute Copyright © 2002 All rights reserved Class files Contains always only 1 class Nested classes are $ 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
36
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
37
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
38
aQute Copyright © 2002 All rights reserved Jar Files: Manifest Manifest Signing of files for security Options: main class, package versions Manifest-Version: 1.0 Created-By: Signtool (signtool 1.1) Comments: PLEASE DO NOT EDIT THIS FILE. YOU WILL BREAK IT. Name: java/awt/Adjustable.class SHA1-Digest: 181v4ECne8mD6ZqcHP3JVD6l17k= Name: java/awt/AWTError.class SHA1-Digest: /ekvoK3hUnQ+amWPopPc2iujHMU= Name: java/awt/AWTEvent.class SHA1-Digest: Jm/yZUSuRs7yZX2IGGVIG4ULD/M=
39
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 VMs do not share byte codes in memory Modern OS'es share executable memory images VM-1VM-2 Class files
40
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
41
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
42
aQute Copyright © 2002 All rights reserved Security anA aB aC A B C Open file C C B B B A Protection Domain Code Source Permission Collection PermissionsPermission File Permissions File Permission Security Manager Access Controller stack foo() bar() open() checkRead(File) check(FilePermission) get stack trace use minimal permission Check permission implies(FilePermission) Policy
43
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
44
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
45
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 Text Component PeerText Field
46
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
47
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
48
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
49
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 Service provider Aggregator OSGi e-box Service provider OSGi e-box OSGi e-box Clients PC, video,...
50
aQute Copyright © 2002 All rights reserved OSGi Framework Life cycle management (install,start,stop, update, uninstall) Registry Http server Logging Client access Remote Admin
51
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...
52
aQute Copyright © 2002 All rights reserved Why did Java get so big? Requirement for perfection APIs must cover all cases perfectly (though they rarely do) Lack of dirty optimization tricks Design by committee Lack of time?
53
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)
54
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 …
55
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
56
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
57
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
58
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
Similar presentations
© 2024 SlidePlayer.com Inc.
All rights reserved.