1 / 169

COMMON JAVA JAVA 数据结构与常用类库简介

COMMON JAVA JAVA 数据结构与常用类库简介. Bingoo. JAVA 类加载. Java Classloading. Why do we care? Because if we’re gonna write code at runtime, we’d better know how to load and use it… Because we don’t really understand classes So… what identifies a class? Its name Its package Its classloader

rafi
Télécharger la présentation

COMMON JAVA JAVA 数据结构与常用类库简介

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. COMMON JAVAJAVA数据结构与常用类库简介 Bingoo

  2. JAVA类加载

  3. Java Classloading • Why do we care? • Because if we’re gonna write code at runtime, we’d better know how to load and use it… • Because we don’t really understand classes • So… what identifies a class? • Its name • Its package • Its classloader • It means that • We can have multiple instances of a class loaded at the same time • Two instances of the same class from different classloaders are not compatible and not assignable • Static variables are static only in the context of a classloader, not globally as we’re always told

  4. Java Classloading • So what is this classloader? • A Java class (subclass of java.lang.ClassLoader), responsible for loading other classes used by the JVM • Classloaders are arranged as a tree • Bootstrap classloader • Loads the Java system • jre/lib/resources.jar – series of resource files • jre/lib/rt.jar – the java.*, javax.*, etc packages • jre/lib/sunrsasign.jar • jre/lib/jsse.jar – secure socket extension • jre/lib/jce.jar – Java cryptography extension • jre/lib/charsets.jar • jre/classes • The important stuff is in rt.jar – the base Java classes

  5. Java Classloading Commandline Java App Tomcat (6) Bootstrap classloader Loads onlybootstrap.jar and tomcat-juli.jar Ext classloader Application/ System classloader Loads Tomcat commons library jars Loads the Application Jars from the classpath Application/ System classloader Common classloader Loads jars in the webapp lib directory WAR 1 classloader WAR 2 classloader

  6. 自定义类加载器加载一个类的步骤 

  7. ClassNotFoundException and NoClassDefFoundError • ClassNotFoundExceptioncomes when JVM tries to load a class at runtime dynamically means you give the name of class at runtime and then JVM tries to load it and if that class is not found in classpath it throws ClassNotFoundException • While in case of NoClassDefFoundError the problematic class was present during Compile time and that's why program was successfully compile but not available during runtime by any reason. 

  8. aopalliance-1.0.jar asm-3.3.jar asm-commons-3.3.jar asm-tree-3.3.jar axis-1.4.jar bcprov-jdk16-1.45.jar cglib-nodep-2.2.jar commons-beanutils-1.8.3.jar commons-codec-1.5.jar commons-collections-3.2.jar commons-discovery-0.4.jar commons-fileupload-1.2.2.jar commons-httpclient-3.1.jar commons-io-2.0.1.jar commons-lang-2.1.jar commons-logging-1.1.1.jar commons-net-2.2.jar commons-pool-1.6.jar commons-ssh-1.5.1.jar dom4j-1.6.1.jar ems-consumer-0.0.1-SNAPSHOT.jar fastjson-1.1.17.jar freemarker-2.3.18.jar guava-12.0.jar hadoop-core-0.20-append-r1056497.jar hbase-0.90.4.jar hessian-3.1.6.jar ibatis-sqlmap-2.3.4.726.M01.jar javassist-3.11.0.GA.jar jline-0.9.94.jar jmockit-0.999.4.jar jsch-0.1.46.jar jsr305-1.3.9.jar junit-4.8.2.jar kafka-0.7.0.jar Linkage-EcsCommon-0.0.1.jar log4j-1.2.16.jar ntfPlat-mailsend-0.0.1.jar ntfplat-send-0.0.1.jar ognl-3.0.4.jar PageSecurity-0.0.2.jar phw-all-0.1.0.jar ProxyForEcsSms-1.0.jar scala-library-2.8.0.jar slf4j-api-1.6.2.jar slf4j-log4j12-1.6.2.jar solr-solrj-3.4.0.jar spring-2.5.6.jar spring-beans-2.5.6.jar spring-context-2.5.6.jar spring-context-support-2.5.6.jar spring-core-2.5.6.jar spring-web-2.5.6.jar spring-webmvc-2.5.6.jar spymemcached-2.8.0.jar struts2-convention-plugin-2.3.1.2.jar struts2-core-2.3.1.2.jar struts2-json-plugin-2.3.1.2.jar wsdl4j-1.6.2.jar xerces-2.6.2.jar xwork-core-2.3.1.2.jar zkclient-0.1.jar zookeeper-3.3.3.jar

  9. JAVA Exception

  10. 几种设计异常的最佳实践 (Best Practises for Designing the API) • 选择Checked还是Unchecked的几个经典依据 • Exception的封装问题 • 如无必要不要创建自己的Exception • 不要用Exception来作流程控制 • 不要轻易的忽略捕获的Exception • 不要简单地捕获顶层的Exception

  11. 三种”情景”导致异常的抛出 • 编程错误导致(Exception due Programming errors) • 这种情景下,异常往往处于编程错误(如:NullPointerException或者 IllegalArgumentException),这时异常一旦抛出,客户端将变得无能为力。 • 客户端代码错误导致(Exception due client code errors) • 客户端试图调用API不允许的操作 • 资源失败导致(Exception due to resource failures) • 如内存不足或网络连接失败导致出现异常等。这些异常的出现客户端可以采取相应的措施来恢复应用程序的继续运行。

  12. Java中异常的类型 Checked and Unchecked Exceptions • A checked exception is one that will be checked by the compiler for a surrounding try/catch block if that method have a throws clause • An unchecked exception, also called a RuntimeException, does not require programmer intervention with a try/catch block • Either there is nothing we can do with this type of problem (sun) • Or, this type of problem can be remedied by fixing code • For example, an ArrayIndexOutOfBounds

  13. Checked or Unchecked exception • 问自己一个问题,“如果这种异常一旦抛出,客户端会做怎样的补救?” • 如果客户端可以通过其他的方法恢复异常,那么这种异常就是checked exception; • 如果客户端对出现的这种异常无能为力,那么这种异常就是Unchecked exception; • 尽量使用unchecked exception来处理编程错误;譬如:NullPointerException , IllegalArgumentException和 IllegalStateException

  14.  保护封装性(Preserve encapsulation) • 不要让你要抛出的checked exception升级到较高的层次。 • 例如,不要让SQLException延伸到业务层。业务层并不需要(不关心?)SQLException。 • 转变SQLException为另外一个checked exception,如果客户端并不需要恢复这种异常的话; • 转变SQLException为一个unchecked exception,如果客户端对这种异常无能为力的话(多数情况);

  15. 使用异常最佳实践 • 总是要做一些清理工作(Always clean up after yourself) • 如果使用一些资源例如数据库连接或者网络连接,请记住要做一些清理工作(如关闭数据库连接或者网络连接) • 要用try-finally来做必要的清理工作 • 不要使用异常来控制流程(Never use exceptions for flow control) • 不要忽略异常 • 当有异常被抛出的时候,如果你不想恢复它,那么你要毫不犹豫的将其转换为unchecked exception,而不是用一个空的catch块或者什么也不做来忽略它,以至于从表面来看象是什么也没有发生一样。 • 不要捕获顶层的Exception • unchecked exception都是RuntimeException的子类,RuntimeException又继承Exception,因此,如果单纯的捕获Exception,那么你同样也捕获了RuntimeException,它将忽略所有的异常,包括unchecked exception. •  Log exceptions just once • Logging the same exception stack trace more than once can confuse the programmer examining the stack trace about the original source of exception. So just log it once.

  16. Add Java Exception Breakpoint

  17. Guava Throwables try{someMethodThatCouldThrowAnything();}catch(IKnowWhatToDoWithThisException e){handle(e);}catch(Throwable t){Throwables.propagateIfInstanceOf(t,IOException.class);Throwables.propagateIfInstanceOf(t,SQLException.class);throwThrowables.propagate(t);}

  18. @Annotations

  19. Annotation Definition • Structured Data • Comparable to records in OCaml @interfaceMyAnnotation { String value(); // member int i() default 123; // member w. default value } @interfaceMarkerAnnotation { // annotation without any members }

  20. Annotation Usage @MyAnnotation(value="text", i=456) void method() { … } // default value for i: 123 @MyAnnotation(value="text") void method2() { … } // special case for members called "value" @MyAnnotation("text") void method3() { … } // parenthesis can be omitted if no members @MarkerAnnotation void method4() { … }

  21. Annotation Members @interface MyAnnotation { intintMember();// primitives StringstringMember();// strings ClassclassMember(); // class literals SomeEnumenumMember();// enums // annotions OnlyThreadWithName annotMember(); // arrays of the above OnlyThreadWithName[]arrayMember(); }

  22. Annotation Targets in Java 5 @Apackage some.package.name; @BclassMyClass { @CObject field; @DMyClass(@EObject param) { field = param; } @FObject method() { @GObject localVar = field; return localVar; } }

  23. The Target annotation @Target(ElementType.TYPE) —can be applied to any element of a class @Target(ElementType.FIELD) —can be applied to a field or property @Target(ElementType.METHOD) —can be applied to a method level annotation @Target(ElementType.PARAMETER) —can be applied to the parameters of a method @Target(ElementType.CONSTRUCTOR) —can be applied to constructors @Target(ElementType.LOCAL_VARIABLE) —can be applied to local variables @Target(ElementType.ANNOTATION_TYPE) —indicates that the declared type itself is an

  24. 告知程序如何处理@Retention java.lang.reflect.AnnotatedElement接口 public Annotation getAnnotation(Class annotationType); public Annotation[] getAnnotations(); public Annotation[] getDeclaredAnnotations(); public boolean isAnnotationPresent(Class annotationType); Class、Constructor、Field、Method、Package等类别,都实现了AnnotatedElement接口

  25. Java Logging

  26.  Logging use-cases • debugging the software during development • help diagnose bugs during production • trace access for security purposes • create data for statistical use • etc

  27. History • System.out.println() • System.err.println() • e.printStackTrace() 

  28. Components Level/ Priority Aplicaction Logger 1..* Appender Filter Layout

  29. LoggerNamedHierarchy Aloggerissaidtobeanancestorofanotherloggerif itsnamefollowedbyadotistheprefixpartinthe descendantloggername. PS: 大小写敏感 root com.site.software com.site.software.model com.site.software.model.dao com.site.software.model.dao.PersonDAOImpl com.site.software.view com.site.softwareisanancestorloggerofthedescendant com.site.software.model.dao ● ●com.site.softwareistheparentloggerofthechild com.site.software.model

  30. Levels Aloggermaybeassignedtoalevel. Propertiesconfigurationfile log4j.rootLogger=ERROR log4j.logger.com.site.software=INFO XMLconfigurationfile Javaconfigurationfile Logger.getRootLogger().setLevel(Level.ERROR); Logger.getLogger(“com.site.software”).setLevel(Level.INFO); levelsareordered TRACE<DEBUG<INFO<WARN<ERROR<FATAL ● ● ● ●

  31. Level/ Priority • FATAL:Displays messages of situations that probably will abort the application. • ERROR:Displays error messages that are unwanted but not interrupt the application. • WARN:Displays messages from dangerous regions for the application, or certain operations use not recommended. • INFO:Displays information messages about the execution of the application, or important events. • DEBUG: Shows debug messages for the application. (Used in development time) • ALL: Show all posts • OFF:Disables all messages.

  32. LevelInheritance TheinheritedlevelforagivenloggerL,isequalto thefirstnon-nulllevelinthelogger named hierarchy, startingatLandproceedingupwardsinthe hierarchytowardstherootlogger. AssignedInherited Levellevel LoggerName root com.site.software com.site.software.model com.site.software.model.dao com.site.software.model.dao.PersonDAOImpl com.site.software.view ERROR WARN INFO null null null ERROR WARN INFO INFO INFO WARN

  33. Level继承1

  34. Level继承2

  35. LoggingRequest Alogrequestoflevelpinaloggerconfigured(either assignedorinherited,whicheverisappropriate)with levelq,isenabledifp>=q. importorg.apache.log4j.Logger; publicclassPersonDAOImpl{ privatefinalLoggerLOG=Logger.getLogger(PersonDAOImpl.class); publicPersonDAOImpl(){ LOG.debug("Youcan'tseemeinthelogbecausedebug<INFO"); LOG.info("Youwillseemeinthelogbecauseinfo=INFO"); LOG.warn("Youwillseemeinthelogbecausewarn>INFO");

  36. Appenders Aloggermaybeassignedtoanappender:anamed outputdestinationyourlogmessagesareforwarded to. #Therootloggerlogstotheconsole log4j.rootLogger=ERROR,con #Thecom.site.softwareloggerlogstoafile log4j.logger.com.site.software=INFO,FileApp #Theconappenderwilllogintheconsole log4j.appender.con=org.apache.log4j.ConsoleAppender #TheFileAppappenderwillloginafile log4j.appender.FileApp=org.apache.log4j.FileAppender

  37. Appenders

  38. AppenderAdditivity EachenabledloggingrequestforagivenloggerL willbeforwardedtoalltheappendersinthatlogger LAaswellasalltheappendershigherHAinthe logger named hierarchy. LoggerName root com.site.software com.site.software.model com.site.software.model.dao com.site.software.view LA con null FileApp,c d e HA con con FileApp,c,con con

  39. Additivity Flag

  40. LayoutConversionPattern Eachappenderhasalayoutcomponentresponsible forformattinglogmessagesaccordinglyto conversionpatterns. log4j.appender.con=org.apache.log4j.ConsoleAppender log4j.appender.con.layout=org.apache.log4j.PatternLayout log4j.appender.con.layout.ConversionPattern=%d[%t]%-5p%m(%c:%L)%n Producedlogs: 2010-05-1419:29:11,996[main]INFOYouwillseemeinthelogbecause info=INFO(com.site.software.model.dao.PersonDAOImpl:10) 2010-05-1419:29:11,997[main]WARNYouwillseemeinthelogbecause warn>INFO(com.site.software.model.dao.PersonDAOImpl:11)

  41. AlotofAppendersandLayouts Appenders ●ConsoleAppenderappendslogeventstoSystem.outorSystem.err ●FileAppenderappendslogeventstoafile ●RollingFileAppenderextendsFileAppendertobackupthelogfileswhen theyreachacertainsize ●DailyRollingFileAppenderextendsFileAppendersothattheunderlyingfile isrolledoveratauserchosenfrequency ●SMTPAppendersendsane-mailwhenaspecificloggingeventoccurs ●JMSAppenderpublisheslogeventstoaJMSTopic ●JDBCAppenderprovidesforsendinglogeventstoadatabase Layouts ●PatternLayoutconfigurablestringpatterninaprintfCfunctionstyle ●XMLLayoutappendslogeventsasaseriesoflog4j:event(log4j.dtd) ●HTMLLayoutoutputseventsinaHTMLtable

  42. The API 1: import org.slf4j.Logger; 2: import org.slf4j.LoggerFactory; 3: 4: public class Wombat { 5: 6: private final Logger logger = LoggerFactory.getLogger(Wombat.class); 7: Integer t; 8: Integer oldT; 9: 10: public void setTemperature(Integer temperature) { 11: 12: oldT = t; 13: t = temperature; 14: 15: logger.debug("Temperature set to {}. Old temperature was {}.", t, oldT); 16: 17: if(temperature.intValue() > 50) { 18: logger.info("Temperature has risen above 50 degrees."); 19: } 20: } 21: }

  43. SLF4J & Logback logback的前世今生 • slf4j由log4j作者Ceki开发,逐步取代apahce commons logging。 • logback由log4j作者Ceki开发,逐步取代log4j。

  44. logback相比较log4j的优势 • slf4j支持参数化 • logger.error(“帐号ID:{}不存在”, userId); • 告别了if(logger.isDebugEnable()) 时代 • 另外logback的整体性能比log4j也较佳,hibernate等项目已经采用了slf4j。

  45. SLF4J and Logback : Dream Dates! • Logback implements SLF4J natively • No computational and memory overhead • Fully compliant to SLF4J • Faster they say! 10 times!! Smaller Blue Print • Core, classic and access modules

  46. Why Logback • Conditional Processing • Good For Dev/Prod switch Is It Worth A Use?

  47. Why Logback • Stack Traces Pointing jar files

  48. ConsoleAppender RollingFileAppender rollover daily or whenever the file size reaches 100MB logback.xml

More Related