1 / 58

Java and embedded systems

Java and embedded systems. About me. Peter Kriens Work as a consultant (mainly for for ERICSSON) Finnasandsvagen 22 43933 Onsala, Sweden +46 705950899 Peter.Kriens@aQute.se. The language. Simple key word based language with lots of curly braces

walker
Download Presentation

Java and embedded systems

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. Java and embedded systems

  2. About me • Peter Kriens • Work as a consultant (mainly for for ERICSSON) • Finnasandsvagen 22 • 43933 Onsala, Sweden • +46 705950899 • Peter.Kriens@aQute.se

  3. 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. 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

  5. The language: Access controls • Access control build into language • public • private • protected • default: package private • deprecated

  6. 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. interface Interfaces public interface Log { public void log(String s);} client uses Log public class SimpleLog { public void log(String s) { System.out.println( s ); }} implements Simple Log IBM Log Motorola Log

  8. Interfaces and message dispatch log(“yes”) invokeinterface an object IBM Log resolve name Log public void log(String s) { System.out.println( s ); } lookup method log(String)

  9. The Language: Nested classes • Used for callbacks • Expensive • > 500 bytes overhead per class • More linking • Requires quirks like final variables • Ugly syntax

  10. com/ibm/log/IBMLog.class com/ibm/log/IBMLog$1.class Anonymous classes • void foo( final int offset ) { • window.addActionListener( new Action() { public void performAction() { _count+=offset; }}}); IBMLog IBMLog$1

  11. 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. 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. Threads Thread Group Thread Thread Data area the heap Stack area Stack area Thread Stack area

  14. Threads: Monitors • Synchronized keyword • Each object has a monitor • Difficult to understand for many people • But powerful • Wait gives up lock

  15. waiting in out synchronized 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

  16. 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. 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. 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. 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. checked! unchecked do not catch Exception hierarchy Object Throwable Error Exception Verify Error ... Error IO Exception ... Exception Runtime Exception NullPointer Exception ... Exception

  21. 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. 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. 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. 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. Dynamic linking Def.class Constants "foo" "bar" Methods 1: invoke 2 Abc.class Constants "bar" "kim" Methods 1: ...

  26. Use A, link in also link in reports A!! 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 refers to extends

  27. 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. db, network, etc Class loaders • Java abstracts where code comes from aClient aClass Loader aFile links in class retrieves byte codes refers to is loaded by belongs to class anObject aClass

  29. 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. Class identity crisis • Two identical class loaded via two different class loaders are different classes! These objects are NOT of the same class aObject bObject bound to AClass aClient AClass is loaded by is loaded by A Loader B Loader Aclass file

  31. 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. 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. 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

  34. 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. 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

  36. 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. 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. 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=

  39. 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

  40. 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. 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. A B B B C C Security Policy implies(FilePermission) anA A Protection Domain implies(FilePermission) foo() Code Source Permission Collection Permissions Permission aB B Check permission File Permissions File Permission bar() stack aC C implies(FilePermission) get stack trace use minimal permission open() Open file Security Manager Access Controller check(FilePermission) checkRead(File)

  43. 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. 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. 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. 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. 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. Java versus C++ • No more stray pointer related core dumps • Useful exceptions • No more memory leaks • Cleaner, simpler syntax • Less performance • Better productivity

  49. 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 OSGi e-box Service provider OSGi e-box Clients PC, video,...

  50. OSGi • Framework • Life cycle management (install,start,stop, update, uninstall) • Registry • Http server • Logging • Client access • Remote Admin

More Related