??xml version="1.0" encoding="utf-8" standalone="yes"?> Most of the puzzles in this chapter were based on name reuse. This section summarizes the various forms of name reuse. An instance method overrides all accessible instance methods with the same signature in superclasses [JLS 8.4.8.1], enabling dynamic dispatch; in other words, the VM chooses which overriding to invoke based on an instance's run-time type [JLS 15.12.4.4]. Overriding is fundamental to object-oriented programming and is the only form of name reuse that is not generally discouraged: A field, static method, or member type hides all accessible fields, static methods, or member types, respectively, with the same name (or, for methods, signature) in supertypes. Hiding a member prevents it from being inherited [JLS 8.3, 8.4.8.2, 8.5]: Methods in a class overload one another if they have the same name and different signatures. The overloaded method designated by an invocation is selected at compile time [JLS 8.4.9, 15.12.2]: A variable, method, or type shadows all variables, methods, or types, respectively, with the same name in a textually enclosing scope. If an entity is shadowed, you cannot refer to it by its simple name; depending on the entity, you cannot refer to it at all [JLS 6.3.1]: Although shadowing is generally discouraged, one common idiom does involve shadowing. Constructors often reuse a field name from their class as a parameter name to pass the value of the named field. This idiom is not without risk, but most Java programmers have decided that the stylistic benefits outweigh the risks: A variable obscures a type with the same name if both are in scope: If the name is used where variables and types are permitted, it refers to the variable. Similarly, a variable or a type can obscure a package. Obscuring is the only kind of name reuse where the two names are in different namespaces: variables, packages, methods, or types. If a type or a package is obscured, you cannot refer to it by its simple name except in a context where the syntax allows only a name from its namespace. Adhering to the naming conventions largely eliminates obscuring [JLS 6.3.2, 6.5]:
A Glossary of Name Reuse
Overriding
class Base {
public void f() { }
}
class Derived extends Base {
public void f() { } // overrrides Base.f()
}
Hiding
class Base {
public static void f() { }
}
class Derived extends Base {
public static void f() { } // hides Base.f()
}
Overloading
class CircuitBreaker {
public void f(int i) { } // int overloading
public void f(String s) { } // String overloading
}
Shadowing
class WhoKnows {
static String sentence = "I don't know.";
public static void main(String[] args) {
String sentence = "I know!"; // shadows static field
System.out.println(sentence); // prints local variable
}
}
class Belt {
private final int size;
public Belt(int size) { // Parameter shadows Belt.size
this.size = size;
}
}
Obscuring
public class Obscure {
static String System; // Obscures type java.lang.System
public static void main(String[] args) {
// Next line won't compile: System refers to static field
System.out.println("hello, obscure world!");
}
}
例:class A
{
public A()
{
System.out.println("A的构造函?/span>");
}
{
System.out.println("A的动态初始化?/span>");
}
static
{
System.out.println("A的静态初始化?/span>");
}
}
class B extends A
{
public B()
{
System.out.println("B的构造函?/span>");
}
{
System.out.println("B的动态初始化?/span>");
}
static
{
System.out.println("B的静态初始化?/span>");
}
}
public class Test
{
public static void main(String[] args)
{
System.out.println("W一ơ生成类B的对象时输出");
new B();
System.out.println("W二ơ生成类B的对象时输出");
new B();
}
}
E序q行l果如下Q?br />
W一ơ生成类B的对象时输出
A的静态初始化?br />B的静态初始化?br />A的动态初始化?br />A的构造函?br />B的动态初始化?br />B的构造函?br />W二ơ生成类B的对象时输出
A的动态初始化?br />A的构造函?br />B的动态初始化?br />B的构造函?img src ="http://www.tkk7.com/cisco/aggbug/95827.html" width = "1" height = "1" />
E序q行l果Q?br />2
B
B
B
1
B
A
A
E序分析Q在该示例程序中Q变量i产生数据成员变量隐藏Q实例方法f()是方法重写,对实例方法的重写会生运行时多态性。staticҎg()也是Ҏ重写Q但q种Ҏ重写不具有运行时多态的特征Q多态特征是针对实例Ҏ而言。因此当子类对象作ؓ父类对象使用Ӟ在输出结果中看到Q只有f()发生了运行时多态?/p>
Every programmer has certain books that he or she wears out by constantly referencing them as a professional. The following books should be on every Java language programmer's bookshelf. Books can be expensive, so this list is intentionally small, limited to the critical ones.
Thinking in Java (Bruce Eckel)
Thinking in Java, 3rd edition
(Bruce Eckel; Prentice Hall PTR, 2002)
Eckel's book is an extremely practical book for learning about how to use object oriented well in a Java language context. Lots of code samples illustrate the concepts as he introduces them. The text is absolutely practical, from a person who doesn't think Java technology is always the right answer. Eckel has lots of experience with lots of languages, and has solid object oriented thinking skills. This book puts those skills in a practical Java language context. He?s also working on a new book called Thinking in Enterprise Java.
Effective Java: Programming Language Guide
(Joshua Bloch; Addison-Wesley, 2001)
This the best book for understanding the principles from which good Java programs are designed. Most of this material is not to be found in other "learning to Java" books. For example, Bloch's chapter on overriding equals()
is one of the best I've ever read. He also includes practical advice on using interfaces instead of abstract classes, and using exceptions intelligently. Bloch was Sun's Java platform libraries architect, so he knows the language from the inside out. In fact, he wrote lots of the useful libraries included with the language. This is a must-read.
The Java Programming Language (Ken Arnold, James Gosling, David Holmes)
The Java Programming Language
(Ken Arnold, James Gosling, David Holmes; Addison-Wesley, 2000)
This is probably the best Java language primer book available. It?s not a formal specification, but a readable introduction to each language feature. It has the right balance of rigor and pedagogy, enabling someone who understands programming to wrap their head around the Java language (and its copious class libraries) quickly.
Concurrent Programming in Java: Design Principles and Patterns (Doug Lea)
Concurrent Programming in Java: Design Principles and Patterns, 2nd edition
(Doug Lea; Addison-Wesley, 1999)
Not every developer needs to know about concurrency in such detail, and not every engineer is up to the level of this book, but there's no better survey of concurrent programming than this. If you?re interested, this is the source. Lea is a professional programmer at SUNY, and his work and ideas related to concurrency have been included in the JDK 5.0 spec (from JSR166), so you can be sure what he has to say about using the Java language effectively is worth listening to. He's a good communicator as well.
Expert One-On-One J2EE Design and Development (Rod Johnson)
Expert One-On-One J2EE Design and Development
(Rod Johnson)
For newcomers to J2EE, this is the only book that really tells it like it is. This book is the result of years of experience of what works and what doesn't, and unlike a lot of other authors, Johnson is willing to say what doesn't. J2EE is often used when it's unnecessary overkill. Johnson's book can help you avoid that.
Refactoring (Martin Fowler, Kent Beck, John Brant, William Opdyke, Don Roberts)
Refactoring: Improving the Design of Existing Code
(Martin Fowler, Kent Beck, John Brant, William Opdyke, Don Roberts; Addison-Wesley, 1999)
Fowler has written some of the most popular programming books ever published, including Analysis Patterns. His book on refactoring is the seminal work on the subject. Refactoring code is a neglected programmer discipline, but an intuitive programmer idea. Refactoring is improving the design of existing code without changing its results. It's the best way to keep your code clean, which keeps it easy to change over time. When do you refactor? Whenever your code 'smells'. Fowler?s book is full of example Java language code. Many Java language integrated development environments (IDEs), including IBM's Eclipse, incorporate Fowler's refactorings, using his names for each one, so it pays to be familiar with things like extract method.
Design Patterns (Erich Gamma, Richard Helm, Ralph Johnson, John Vlissides)
Design Patterns: Elements of Reusable Object Oriented Software
(Erich Gamma, Richard Helm, Ralph Johnson, John Vlissides; Addison-Wesley, 1997)
This is one of the more famous books among professional programmers, and has become known as "the Gang of Four (GOF) book," based on the collective nickname of the authors. Patterns are reusable ways of thinking about and solving common programming problems. Learning patterns is a discipline. Using them well (or knowing when not to use them) is a skill. Ignoring them is a mistake. All of the examples in the book are in C++, but the Java language was born from that world, and it?s relatively simple for Java language programmers to relate to how to implement the patterns in the Java language. Being familiar with patterns, and knowing how to use them well, makes programming easier. It also makes communicating with other programmers easier, because patterns are a shortcut way to describe lots of related programming concepts that work together in a common solution to a common problem. Some of the more common ones, like Factory Method, are ubiquitous, even in the Java language itself. On the subject of using patterns wisely, you also might want to read Joshua Kerievsky's Refactoring to Patterns, which says you should let your code tell you when to implement a pattern.
Patterns of Enterprise Application Architecture (Martin Fowler)
Patterns of Enterprise Application Architecture
(Martin Fowler; Addison-Wesley, 2002)
Enterprise development certainly presents more challenges than small, one-off projects. That doesn?t mean that all enterprise development challenges are new. In fact, more often than not, it has been done before. In many cases, Fowler's worked on projects that did it. His book talks about some of the common solutions, and offers guidance on usage, compromises, and alternatives. Fowler includes some familiar patterns here, such as Model View Controller (MVC), but he also includes some that may be new to you, like Page Controller for handling requests for specific pages or actions on a Web site. As with most patterns, once you read many of them, you think, 'I knew that already'. Perhaps, but it helps to have a common presentation of the pattern to refer to. That kind of reference is a superb help on large projects with multiple components developed by different people.
UML Distilled: A Brief Guide to the Standard Object Modeling Language
(Martin Fowler; Addison-Wesley 2003)
UML is an important common visual communication language for professional programmers, but it's overused and grossly abused. You don't need to know much to communicate with UML. Martin's distillation gives you the essentials. In fact, the inside front and back covers give you almost everything you'll ever use on a regular basis. All of the code behind the UML examples in the book is Java code.
Test-Driven Development: By Example (Kent Beck)
Test-Driven Development: By Example
(Kent Beck; Addison-Wesley 2002)
Test-first programming will revolutionize your programming, and can help you become one of the better programmers out there. Writing tests before you write code is an initially awkward, but powerful development skill. By writing tests first, you can keep your code simpler, and you can be sure it works from the start (practicing what he preaches, Beck co-wrote JUnit, the most prevalent testing framework for the Java language, test-first). Beck?s book is the definitive source, and the extended Money example is in the Java language. Beck walks through how to think test-first, which can be an initial barrier for many programmers.
The Pragmatic Programmer: From Journeyman to Master (Andy Hunt and Dave Thomas)
The Pragmatic Programmer: From Journeyman to Master
(Andrew Hunt and David Thomas; Addison-Wesley 1999)
Being an object oriented purist has its advantages. In today?s complex world, you often have to compromise in order to get things done as a Java language developer. The guiding principle is to be pragmatic. Hunt and Thomas talk about how to do that, without compromising what?s really important. This isn?t a Java language book, but it?s a critical mindset book for Java language developers. For example, I don't know of a single programmer who couldn't benefit from the admonition to "fix the problem, not the blame" and to sign your work like a proud craftsman.
Peopleware: Productive Projects and Teams (Tom DeMarco and Timothy Lister)
Peopleware: Productive Projects and Teams
(Tom DeMarco, Timothy Lister; Dorset House, 1999)
All of the other books on this list are at least somewhat technical. This one is not. In all of the technical jargon, and in the sea of acronyms, sometimes software developers and managers forget that people make software. DeMarco and Lister remind us of that fact, and why it should make a difference. This isn?t a book about a particular programming language, but every Java language programmer should read it. There are other good books about how killing programmers is counterproductive for managers, but this is one of the best.
There are more Web sites than you could visit in a lifetime, that is, if you wanted to digest any of their content. An exhaustive list of sites with content about some aspect of the Java language would be ridiculously large. The following sites are tried and true.
Sun's Java language site
This is Sun?s main Java language site. You will find yourself visiting this site very frequently as a Java language developer. The following links are particularly important, especially to new Java language developers:
IBM's developerWorks
This may seem shameless self-promotion, but developerWorks is a great resource for tutorials and articles about Java language tools and techniques. Content ranges from a beginner's guide to learning the language, to advanced concurrency techniques. You can search content by topic, and can browse by type.
The Apache Software Foundation
The Apache Software Foundation
The Apache site is home to many reusable libraries (in the Commons area) and tools to help Java developers. It?s all Open Source, so download what you want. Many extremely popular Java language libraries and tools (such as Struts, Ant, and Tomcat) began as Apache projects. The Jakarta area has most of the emerging Java language stuff.
Eclipse
There are several good Java language integrated development environments (IDEs). Eclipse (from IBM) is one of the newest, and is rapidly becoming the premier IDE for Java language development. It?s entirely Open Source, which means it?s free. This site contains all sorts of resources for learning about how to use Eclipse effectively. It also has information about the Standard Widget Toolkit (SWT), a lighter weight alternative to Swing.
Eclipse Plugin Central and EclipsePlugins
Eclipse Plugin Central
and EclipsePlugins
Eclipse is based on a plug-in architecture. In fact, the Java language development components of Eclipse are plug-ins. But there are literally hundreds of plug-ins for everything from Web development to playing games within the Eclipse environment. These two sites list most of them, by category, and are searchable. They are excellent resources. If you use Eclipse, and want to do something new in your development environment, odds are good that there?s a plug-in for it, and that you can find it here. Both sites let people review the plug-ins, so you can get some information about which ones are good and which ones aren?t worth your time.
JUnit.org
JUnit is the seminal unit testing framework for the Java language. The site contains the latest and greatest version, plus a huge number of other resources about testing (in the Java language and others) at various levels, for desktop apps, Web apps, J2EE apps, etc. If you want to find testing resources, this is the best place to start.
TheServerSide.com
If you are (or will be) involved with Java language development on the server side, this site is a vital resource. You can find articles here on JBoss, J2EE, LDAP, Struts, and a host of other topics, and it?s fully searchable. They don't simply describe features of the Java language, or supporting libraries. They take it one step further to describe novel uses of libraries (such as using Jakarta's Velocity as a rules engine, rather than a templating engine). They also provide running commentary on the state of the Java language (a current article is titled Java is boring, by Tim Bray). One of the better common features of the site are matrix comparisons of Java language tools and products (application servers, etc.).
Bruce Eckel's MindView, Inc.
Eckel wrote several books about "thinking in" the Java language, Python, and C++. His Thinking in Java was particularly helpful to me as I was learning the language. It?s practical and to the point, with excellent insights about how to think in objects in a Java language context. You can download free electronic copies of all of his books at this site. He also has written many good articles, and he?s got links to all of them here (including articles on Jython, Java vs. .NET, etc.).
ONJava.com
O?Reilley has published excellent books about programming languages and tools for years. Their Java-language focused Web site is just as good. It has articles on various Java language tools (like JDOM and Hibernate), different areas for different parts of the Java Platform (like J2SE and J2EE). It?s fully searchable. They have excellent articles and tutorials. The site is arranged by topic. Some examples include Java and XML, Java Security, Wireless Java, and Java SysAdmin. The site also has a link to the O'Reilley Learning Lab, where you can take online courses (Java language-related and otherwise). They aren't free, but many count toward college credit, so you get a convenient way to learn skills, and some credentials as well.
java.net Communities
There are multiple "communities" here, with subject-specific forums and articles. For example, the Java Desktop community has all sorts of stuff related to Java language development for the desktop. The Java Patterns community might be of particular interest as a portal for pattern resources from a Java language perspective. There is also a community for Java User Groups (JUGs), where you can find information about creating, joining and running a JUG.
Abstract Windows Toolkit (AWT) is the original Java GUI tool kit. AWT's main advantages are that it comes standard with every version of Java technology, including Java implementations in old Web browsers, and it is very stable. This means you do not need to install it, you can depend on it being available everywhere you find a Java runtime environment, and it will have the features you expect.
A look at Swing
Java Swing, also known as a part of the Java Foundation Classes (JFC), was an attempt to solve most of AWT's shortcomings. In Swing, Sun created a very well-engineered, flexible, powerful GUI tool kit. Unfortunately, this means Swing takes time to learn, and it is sometimes too complex for common situations.
SWT is a low-level GUI tool kit comparable in concept to AWT. JFace is a set of enhanced components and utility services to make building GUIs with SWT easier. The builders of SWT learned from the AWT and Swing implementations and tried to build a system that had the advantages of both without their disadvantages. In many ways, they succeeded.
Conclusion
In most cases, the decision is between Swing and SWT combined with JFace. In general, each of these tool kits is complete and powerful enough to build full-function GUIs, but Swing is generally superior to SWT alone (used without JFace). Swing has the advantage of being built into Java technology, is completely portable, and arguably has a better architecture. Swing also has the advantage for advanced graphical applications. SWT has the advantage of being implemented as a native application which increases the performance and native compatibility of SWT-based GUIs.
If you are developing only for one platform, SWT has an advantage in host compatibility, including integration with host features, such as use of ActiveX controls under Windows.
The original (full version) article: http://www-128.ibm.com/developerworks/opensource/library/os-swingswt/
Item 1: Consider providing static factory methods instread of constructs
Item 2: Enforce the singleton property with a private constructor
Item 3: Enforce noninstantiability with a private constructor
Item 4: Avoid creating duplicate objects
Item 5: Eliminate obsolete object reference
Item 6: Avoid finalizers
Chapter 3. Methods Common to All Objects
Item 7: Obey the general contract when overriding equals
Item 8: Always override hashCode when you override equals
Item 9: Always override toString
Item 10: Override clone judiciously
Item 11: Consider implementing Comparable
Chapter 4. Classes and Interfaces
Item 12: Minimize the accessibility of classes and members
Item 13: Favor immutability
Item 14: Favor composition over inheritance
Item 15: Design and document for inheritance or else prohibit it
Item 16: Prefer interfaces to abstract classes
Item 17: Use interfaces only to define types
Item 18: Favor static member classes over nonstatic
Chapter 5. Substitutes for C Constructs
None of my business, neglect.
Chapter 6. Methods
Item 23: Check parameters for validity
Item 24: Make defensive copies when needed
Item 25: Design method signatures carefully
Item 26: Use overloading judiciously
Item 27: Return zero-length arrays, not nulls
Item 28: Write doc comments for all exposed API elements
Chapter 7. General Programming
Item 29: Minimize the scope of local variables
Item 30: Know and use the libraries
Item 31: Avoid float and double if exact answers are required
Item 32: Avoid strings where other types are more appropriate
Item 33: Beware the performance of string concatenation
Item 34: Refer to objects by their interfaces
Item 35: Prefer interfaces to reflection
Item 36: Use native methods judiciously
Item 37: Optimize judiciously
Item 38: Adhere to generally accepted naming conventions
一 问题的提?/span>
Java的一个重要优点就是通过垃圾攉?Garbage CollectionQGC)自动理内存的回ӞE序员不需要通过调用函数来释攑ֆ存。因此,很多E序员认为Java不存在内存泄漏问题,或者认为即使有内存泄漏也不是程序的责QQ而是GC或JVM的问题。其实,q种x是不正确的,因ؓJava也存在内存泄Ԍ但它的表CC++不同?/p>
随着来多的服务器E序采用Java技术,例如JSPQServletQ?EJB{,服务器程序往往长期q行。另外,在很多嵌入式pȝ中,内存的总量非常有限。内存泄露问题也变得十分关键,即每次q行量泄漏Q长期运行之后,pȝ也是面崩溃的危险?/p>
?Java是如何管理内?/span>
Z判断Java中是否有内存泄露Q我们首先必M解Java是如何管理内存的。Java的内存管理就是对象的分配和释N题。在Java中,E序员需要通过关键字new为每个对象申请内存空?(基本cd除外)Q所有的对象都在?(Heap)中分配空间。另外,对象的释放是由GC军_和执行的。在Java中,内存的分配是q序完成的Q而内存的释放是有GC完成的,q种收支两条U的Ҏ实化了E序员的工作。但同时Q它也加重了JVM的工作。这也是JavaE序q行速度较慢的原因之一。因为,GCZ能够正确释放对象QGC必须监控每一个对象的q行状态,包括对象的申诗引用、被引用、赋值等QGC都需要进行监控?/p>
监视对象状态是Z更加准确地、及时地释放对象Q而释攑֯象的Ҏ原则是该对象不再被引用?/p>
Z更好理解GC的工作原理,我们可以对象考虑为有向图的顶点,引用关p考虑为图的有向边Q有向边从引用者指向被引对象。另外,每个U程对象可以作ؓ一个图的v始顶点,例如大多E序从mainq程开始执行,那么该图是以mainq程点开始的一|树。在q个有向图中Q根点可达的对象都是有效对象,GC不回收q些对象。如果某个对?(q通子?与这个根点不可?注意Q该图ؓ有向?Q那么我们认?q些)对象不再被引用,可以被GC回收?/p>
以下Q我们D一个例子说明如何用有向图表C内存管理。对于程序的每一个时刻,我们都有一个有向图表示JVM的内存分配情c以下右图,是左边E序q行到第6行的C意图?/p>
Java使用有向囄方式q行内存理Q可以消除引用@环的问题Q例如有三个对象Q相互引用,只要它们和根q程不可辄Q那么GC也是可以回收它们的。这U方式的优点是管理内存的_ֺ很高Q但是效率较低。另外一U常用的内存理技术是使用计数器,例如COM模型采用计数器方式管理构Ӟ它与有向囄比,_ֺ行低(很难处理循环引用的问?Q但执行效率很高?/p>
?什么是Java中的内存泄露
下面Q我们就可以描述什么是内存泄漏。在Java中,内存泄漏是存在一些被分配的对象,q些对象有下面两个特点,首先Q这些对象是可达的,卛_有向图中Q存在通\可以与其相连Q其ơ,q些对象是无用的Q即E序以后不会再用这些对象。如果对象满两个条gQ这些对象就可以判定为Java中的内存泄漏Q这些对象不会被GC所回收Q然而它却占用内存?/p>
在C++中,内存泄漏的范围更大一些。有些对象被分配了内存空_然后却不可达Q由于C++中没有GCQ这些内存将永远收不回来。在Java中,q些不可辄对象都由GC负责回收Q因此程序员不需要考虑q部分的内存泄露?/p>
通过分析Q我们得知,对于C++Q程序员需要自q理边和顶点,而对于JavaE序员只需要管理边可以了(不需要管理顶点的释放)。通过q种方式QJava提高了编E的效率?/p>
因此Q通过以上分析Q我们知道在Java中也有内存泄漏,但范围比C++要小一些。因为Java从语a上保证,M对象都是可达的,所有的不可辑֯象都由GC理?/p>
对于E序员来_GC基本是透明的,不可见的。虽Ӟ我们只有几个函数可以讉KGCQ例如运行GC的函数System.gc()Q但是根据Java语言规范定义Q?该函C保证JVM的垃圾收集器一定会执行。因为,不同的JVM实现者可能用不同的法理GC。通常QGC的线E的优先U别较低。JVM调用GC的策略也有很多种Q有的是内存使用到达一定程度时QGC才开始工作,也有定时执行的,有的是^~执行GCQ有的是中断式执行GC。但通常来说Q我们不需要关心这些。除非在一些特定的场合QGC的执行媄响应用程序的性能Q例如对于基于Web的实时系l,如网l游戏等Q用户不希望GCH然中断应用E序执行而进行垃圑֛Ӟ那么我们需要调整GC的参敎ͼ让GC能够通过q缓的方式释攑ֆ存,例如垃圑֛收分解ؓ一pd的小步骤执行QSun提供的HotSpot JVM支持这一Ҏ?/p>
下面l出了一个简单的内存泄露的例子。在q个例子中,我们循环甌Object对象Qƈ所甌的对象放入一个Vector中,如果我们仅仅释放引用本nQ那么Vector仍然引用该对象,所以这个对象对GC来说是不可回收的。因此,如果对象加入到Vector后,q必MVector中删除,最单的Ҏ是Vector对象讄为null?/p>
?如何内存泄?/span>
最后一个重要的问题Q就是如何检Java的内存泄漏。目前,我们通常使用一些工h查JavaE序的内存泄漏问题。市Z已有几种专业查Java内存泄漏的工P它们的基本工作原理大同小异,都是通过监测JavaE序q行Ӟ所有对象的甌、释攄动作Q将内存理的所有信息进行统计、分析、可视化。开发h员将Ҏq些信息判断E序是否有内存泄漏问题。这些工具包括Optimizeit ProfilerQJProbe ProfilerQJinSight , Rational 公司的Purify{?/p>
下面Q我们将单介lOptimizeit的基本功能和工作原理?/p>
Optimizeit Profiler版本4.11支持ApplicationQAppletQServlet和Romote Application四类应用Qƈ且可以支持大多数cd的JVMQ包括SUN JDKpdQIBM的JDKpdQ和Jbuilder的JVM{。ƈ且,该Y件是由Java~写Q因此它支持多种操作pȝ。Optimizeitpdq包括Thread Debugger和Code Coverage两个工具Q分别用于监运行时的线E状态和代码覆盖面?/p>
当设|好所有的参数了,我们可以在OptimizeIt环境下运行被程序,在程序运行过E中QOptimizeit可以监视内存的用曲U?如下?Q包括JVM甌的堆(heap)的大,和实际用的内存大小。另外,在运行过E中Q我们可以随时暂停程序的q行Q甚臛_行调用GCQ让GCq行内存回收。通过内存使用曲线Q我们可以整体了解程序用内存的情况。这U监对于长期运行的应用E序非常有必要,也很Ҏ发现内存泄露?/p>
在运行过E中Q我们还可以从不同视角观查内存的使用情况QOptimizeit提供了四U方式:
在运行过E中Q我们可以随时观察内存的使用情况Q通过q种方式Q我们可以很快找到那些长期不被释放,q且不再使用的对象。我们通过查这些对象的生存周期Q确认其是否为内存泄霌Ӏ在实践当中Q寻扑ֆ存泄露是一仉帔R烦的事情Q它需要程序员Ҏ个程序的代码比较清楚Qƈ且需要丰富的调试l验Q但是这个过E对于很多关键的JavaE序都是十分重要的?/p>
lg所qͼJava也存在内存泄露问题,其原因主要是一些对象虽然不再被使用Q但它们仍然被引用。ؓ了解册些问题,我们可以通过软g工具来检查内存泄Ԍ查的主要原理是暴露出所有堆中的对象Q让E序员寻N些无用但仍被引用的对象?br />
Further reading:The Truth About Garbage Collection
Thinking in javaW四章的内容是关于内存分配和初始化的,对这一章的学习带出了我以往学习中的一个模p点:I竟什么是堆存?Heap)?什么是栈存?Stack)?有什么区别呢?M不少资料,补了q一?觉得非常受用.
2.1 内存分配{略
按照~译原理的观?E序q行时的内存分配有三U策?分别是静态的,栈式?和堆式的.
静态存储分配是指在~译时就能确定每个数据目标在q行时刻的存储空间需?因而在~译时就可以l他们分配固定的内存I间.q种分配{略要求E序代码中不允许有可变数据结?比如可变数组)的存?也不允许有嵌套或者递归的结构出?因ؓ它们都会D~译E序无法计算准确的存储空间需?
栈式存储分配也可UCؓ动态存储分?是由一个类g堆栈的运行栈来实现的.和静态存储分配相?在栈式存储方案中,E序Ҏ据区的需求在~译时是完全未知?只有到运行的时候才能够知道,但是规定在运行中q入一个程序模块时,必须知道该程序模块所需的数据区大小才能够ؓ其分配内?和我们在数据l构所熟知的栈一?栈式存储分配按照先进后出的原则进行分配?BR>静态存储分配要求在~译时能知道所有变量的存储要求,栈式存储分配要求在过E的入口处必ȝ道所有的存储要求,而堆式存储分配则专门负责在编译时或运行时模块入口处都无法定存储要求的数据结构的内存分配,比如可变长度串和对象实例.堆由大片的可利用块或I闲块组?堆中的内存可以按照Q意顺序分配和释放.
2.2 堆和栈的比较
上面的定义从~译原理的教材中ȝ而来,除静态存储分配之?都显得很呆板和难以理?下面撇开静态存储分?集中比较堆和?
从堆和栈的功能和作用来通俗的比?堆主要用来存攑֯象的Q栈主要是用来执行程序的.而这U不同又主要是由于堆和栈的特点决定的:
在编E中Q例如C/C++中,所有的Ҏ调用都是通过栈来q行?所有的局部变?形式参数都是从栈中分配内存空间的。实际上也不是什么分?只是从栈向上用p,好像工厂中的传送带(conveyor belt)一?Stack Pointer会自动指引你到放东西的位|?你所要做的只是把东西放下来就?退出函数的时候,修改栈指针就可以把栈中的内容销?q样的模式速度最?当然要用来运行程序了.需要注意的?在分配的时?比如Z个即要调用的程序模块分配数据区?应事先知道这个数据区的大?也就说是虽然分配是在E序q行时进行的,但是分配的大多是定?不变?而这?大小多少"是在~译时确定的,不是在运行时.
堆是应用E序在运行的时候请求操作系l分配给自己内存Q由于从操作pȝ理的内存分?所以在分配和销毁时都要占用旉Q因此用堆的效率非常?但是堆的优点在于,~译器不必知道要从堆里分配多存储空_也不必知道存储的数据要在堆里停留多长的时?因此,用堆保存数据时会得到更大的灵zL。事实上,面向对象的多态?堆内存分配是必不可少?因ؓ多态变量所需的存储空间只有在q行时创Z对象之后才能定.在C++中,要求创徏一个对象时Q只需用new命o~制相关的代码即可。执行这些代码时Q会在堆里自动进行数据的保存.当然Qؓ辑ֈq种灉|性,必然会付Z定的代h:在堆里分配存储空间时会花掉更长的旉Q这也正是导致我们刚才所说的效率低的原因,看来列宁同志说的?人的优点往往也是人的~点,人的~点往往也是人的优点(晕~).
2.3 JVM中的堆和?
JVM是基于堆栈的虚拟?JVM为每个新创徏的线E都分配一个堆?也就是说,对于一个JavaE序来说Q它的运行就是通过对堆栈的操作来完成的。堆栈以帧ؓ单位保存U程的状态。JVM对堆栈只q行两种操作:以为单位的压栈和出栈操作?BR>我们知道,某个U程正在执行的方法称为此U程的当前方?我们可能不知?当前Ҏ使用的UCؓ当前帧。当U程ȀzM个JavaҎ,JVM׃在线E的Java堆栈里新压入一个。这个自然成ؓ了当前.在此Ҏ执行期间,q个帧将用来保存参数,局部变?中间计算q程和其他数?q个帧在q里和编译原理中的活动纪录的概念是差不多?
从Java的这U分配机制来?堆栈又可以这L?堆栈(Stack)是操作系l在建立某个q程时或者线E?在支持多U程的操作系l中是线E?个线E徏立的存储区域Q该区域h先进后出的特性?BR>每一个Java应用都唯一对应一个JVM实例Q每一个实例唯一对应一个堆。应用程序在q行中所创徏的所有类实例或数l都攑֜q个堆中,q由应用所有的U程׃n.跟C/C++不同QJava中分配堆内存是自动初始化的。Java中所有对象的存储I间都是在堆中分配的Q但是这个对象的引用却是在堆栈中分配,也就是说在徏立一个对象时从两个地斚w分配内存Q在堆中分配的内存实际徏立这个对象,而在堆栈中分配的内存只是一个指向这个堆对象的指?引用)而已?/P>
2.4 GC的思?BR>JavaZ么慢?JVM的存在当然是一个原?但有,在Java?除了单类?int,char{?的数据结?其它都是在堆中分配内?所以说Java的一切都是对?Q这也是E序慢的原因之一?BR>我的x?应该说代表TIJ的观?,如果没有Garbage Collector(GC),上面的说法就是成立的.堆不象栈是连l的I间,没有办法指望堆本w的内存分配能够象堆栈一h有传送带般的速度,因ؓ,谁会Z整理庞大的堆I间,让你几乎没有延迟的从堆中获取新的I间?
q个时?GC站出来解决问?我们都知道GC用来清除内存垃圾,为堆腑ևI间供程序?但GC同时也担负了另外一个重要的d,是要让Java中堆的内存分配和其他语言中堆栈的内存分配一样快,因ؓ速度的问题几乎是众口一词的对Java的诟?要达到这L目的,必M堆的分配也能够做到象传送带一?不用自己操心LI闲I间.q样,GC除了负责清除Garbage?q要负责整理堆中的对?把它们{Ud一个远Garbage的纯净I间中无间隔的排列v?p堆栈中一L?q样Heap Pointer可以方便的指向传送带的v始位|?或者说一个未使用的空?Z一个需要分配内存的对象"指引方向".因此可以q样?垃圾攉影响了对象的创徏速度,听v来很?对不?
那GC怎样在堆中找到所有存zȝ对象?前面说了,在徏立一个对象时Q在堆中分配实际建立q个对象的内?而在堆栈中分配一个指向这个堆对象的指?引用),那么只要在堆?也有可能在静态存储区)扑ֈq个引用,可以跟t到所有存zȝ对象.扑ֈ之后,GC它们从一个堆的块中移到另外一个堆的块?q将它们一个挨一个的排列h,p我们上面说的那样,模拟Z一个栈的结?但又不是先进后出的分?而是可以L分配?在速度可以保证的情况下,Isn't it great?
但是Q列宁同志说?人的优点往往也是人的~点,人的~点往往也是人的优点(再晕~~).GC()的运行要占用一个线E?q本w就是一个降低程序运行性能的缺?更何况这个线E还要在堆中把内存翻来覆ȝ折腾.不仅如此,如上面所?堆中存活的对象被搬移了位|?那么所有对q些对象的引用都要重新赋?q些开销都会D性能的降?
此消彼长,GC()的优点带来的效益是否盖过了它的缺点导致的损失,我也没有太多的体?Bruce Eckel 是Java的支持者,王婆卖瓜Q话不能全信.个hȝ感觉?Javaq是很慢,它的发展q需要时?
上面的体会是我看了TIJ.3rdEdition.Revision4.0中第四章之后得出?内容和前面的有些不同.我没有看q侯L中文版本,但我觉得,在关键问题上,原版的TIJ的确更值得一?所以和中文版配合v来学习是比较不错的选择.
我只能算一个Java的初学?没想到v了这么个题目,却受到这么多人的x,ƣ喜之余,也决心尽力写好下面的每一?不过q一完?我就该准备ʎ签证了,如果成功,那就要等??7号CS的研I生院开学之?才有旉会开始研I下一章了,希望可以多从原版中获取一点经?