Survey
* Your assessment is very important for improving the workof artificial intelligence, which forms the content of this project
* Your assessment is very important for improving the workof artificial intelligence, which forms the content of this project
Java and embedded systems About me Peter Kriens Work as a consultant (mainly for for ERICSSON) Finnasandsvagen 22 43933 Onsala, Sweden +46 705950899 [email protected] 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 Class names are globally unique watch case sensitiveness on PC’s redundant 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 public interface Log { public void log(String s); } client uses public class SimpleLog { public void log(String s) { System.out.println( s ); } } Simple Log aQute Copyright © 2002 All rights reserved interface Log implements IBM Log Motorola Log Interfaces and message dispatch log(“yes”) invokeinterface IBM Log an object resolve name Log public void log(String s) { System.out.println( s ); } lookup method log(String) 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; }}}); com/ibm/log/IBMLog.class IBMLog com/ibm/log/IBMLog$1.class IBMLog$1 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 Threadgroups Thread thread = new Thread() { public void run() { …. } }; Treat a group of threads as one Monitor life of threads Expensive resource! Stack Scheduling aQute Copyright © 2002 All rights reserved Threads Thread Group Thread Thread Data area the heap Stack area Stack area Thread Stack area 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(); } } Queue waiting Object pop() { synchronized( _vector ) { while ( _vector.size() == 0 ) wait(); Object o = _vector.elementAt(0); _vector.removeElementAt(0); } } in aQute Copyright © 2002 All rights reserved synchronized monitor out aThread aThread 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 checked! do not catch Error Exception unchecked Verify Error ... Error IO Exception ... Exception Runtime Exception NullPointer Exception aQute Copyright © 2002 All rights reserved ... Exception 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 Static initialization when first referenced Addition of new variables/methods/signatures Removal of unused methods static { doSomething(); } Size/Performance hit aQute Copyright © 2002 All rights reserved Dynamic linking Def.class Constants "foo" "bar" Abc.class Constants "bar" "kim" Methods 1: invoke 2 Methods 1: ... 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! Use A, link in aClient refers to also link in A B extends 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 links in class aClass Loader retrieves byte codes aFile refers to is loaded by anObject aQute Copyright © 2002 All rights reserved belongs to class aClass db, network, etc 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! aObject These objects are NOT of the same class bObject bound to AClass aClient AClass is loaded by is loaded by A Loader aQute Copyright © 2002 All rights reserved Aclass file B Loader Type safety Java is type safe by design However, an object can be cast to another class. String s = (String) new Integer() Does not compile, does not get past verifier Allows optimizations 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=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 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 1572 Mon Nov 22 12:21:44 2759 Mon Nov 22 12:21:44 1441 Mon Nov 22 12:21:44 32 Mon Nov 22 12:21:44 3486 Mon Nov 22 12:21:44 11401 Mon Nov 22 12:21:44 2481 Mon Nov 22 12:21:44 aQute Copyright © 2002 All rights reserved CET CET CET CET CET CET CET CET 1999 1999 1999 1999 1999 1999 1999 1999 ericsson/net/ipv4/resources.txt ericsson/net/ipv4/UDP.class ericsson/net/ipv4/TCP.class ericsson/net/ipv4/ICMP.class ericsson/rcur/btest/resources.txt ericsson/rcur/btest/Lme.class ericsson/net/ipv4/IP.class ericsson/net/ipv4/Network.class 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= 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: Java: char c[100]; int x = (int) *c; 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 implies(FilePermission) anA A Policy Protection Domain implies(FilePermission) foo() aB B Code Source Permission Collection Permissions Permission File Permissions File Permission Check permission bar() stack aC C open() Open file Security Manager checkRead(File) aQute Copyright © 2002 All rights reserved A B B B C C check(FilePermission) implies(FilePermission) get stack trace use minimal permission Access Controller 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 aQute Copyright © 2002 All rights reserved Text Component PeerText Field 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 Service Service provider provider aQute Copyright © 2002 All rights reserved Aggregator OSGi OSGi e-box e-box OSGi Clients PC, e-box video,... 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 Java Secrets David Flanagan. ISBN 1-56592-183-6 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 Java Security Scott Oaks. ISBN 1-56592-403-7 Java Developers Almanac Tim Lindholm, Frank Yellin, ISBN 0-201-63452-X Patrick Chan. ISBN 0-201-37967-8 Late night IFC Jason Beaver, Jamie Costa, Jason Wehling. ISBN 156276-540-X aQute Copyright © 2002 All rights reserved