1. Trang chủ
  2. » Công Nghệ Thông Tin

Thinking in Java_ Bruce Eckel

836 601 0
Tài liệu đã được kiểm tra trùng lặp

Đang tải... (xem toàn văn)

Tài liệu hạn chế xem trước, để xem đầy đủ mời bạn chọn Tải xuống

THÔNG TIN TÀI LIỆU

Thông tin cơ bản

Định dạng
Số trang 836
Dung lượng 4,15 MB

Nội dung

Thinking in Java Bruce Eckel Comments from readers: Much better than any other Java book I’ve seen Make that “by an order of magnitude” very complete, with excellent right-to-the-point examples and intelligent, not dumbed-down, explanations In contrast to many other Java books I found it to be unusually mature, consistent, intellectually honest, well-written and precise IMHO, an ideal book for studying Java Anatoly Vorobey, Technion University, Haifa, Israel One of the absolutely best programming tutorials I’ve seen for any language Joakim Ziegler, FIX sysop Thank you for your wonderful, wonderful book on Java Dr Gavin Pillay, Registrar, King Edward VIII Hospital, South Africa Thank you again for your awesome book I was really floundering (being a non-C programmer), but your book has brought me up to speed as fast as I could read it It’s really cool to be able to understand the underlying principles and concepts from the start, rather than having to try to build that conceptual model through trial and error Hopefully I will be able to attend your seminar in the not-too-distant future Randall R Hawley, Automation Technician, Eli Lilly & Co The best computer book writing I have seen Tom Holland This is one of the best books I’ve read about a programming language… Chapter 16 on design patterns is one of the most interesting things I’ve read in a long time Ilan Finci, graduate student and teaching assistant, Institute of Computer Science, The Hebrew University of Jerusalem, Israel The best book ever written on Java Ravindra Pai, Oracle Corporation, SUNOS product line This is the best book on Java that I have ever found! You have done a great job Your depth is amazing I will be purchasing the book when it is published I have been learning Java since October 96 I have read a few books, and consider yours a “MUST READ.” These past few months we have been focused on a product written entirely in Java Your book has helped solidify topics I was shaky on and has expanded my knowledge base I have even used some of your explanations as information in interviewing contractors to help our team I have found how much Java knowledge they have by asking them about things I have learned from reading your book (e.g the difference between arrays and Vectors) Your book is great! Steve Wilkinson, Senior Staff Specialist, MCI Telecommunications Great book Best book on Java I have seen so far Jeff Sinclair, Software Engineer, Kestral Computing Thank you for Thinking in Java It’s time someone went beyond mere language description to a thoughtful, penetrating analytic tutorial that doesn’t kowtow to The Manufacturers I’ve read almost all the others–only yours and Patrick Winston’s have found a place in my heart I’m already recommending it to customers Thanks again Richard Brooks, Java Consultant, Sun Professional Services, Dallas Other books cover the WHAT of Java (describing the syntax and the libraries) or the HOW of Java (practical programming examples) Thinking in Java is the only book I know that explains the WHY of Java; why it was designed the way it was, why it works the way it does, why it sometimes doesn’t work, why it’s better than C++, why it’s not Although it also does a good job of teaching the what and how of the language, Thinking in Java is definitely the thinking person’s choice in a Java book Robert S Stephenson Thanks for writing a great book The more I read it the better I like it My students like it, too Chuck Iverson I just want to commend you for your work on Thinking in Java It is people like you that dignify the future of the Internet and I just want to thank you for your effort It is very much appreciated Patrick Barrell, Network Officer Mamco-QAF Mfg Inc Most of the Java books out there are fine for a start, and most just have beginning stuff and a lot of the same examples Yours is by far the best advanced thinking book I’ve seen Please publish it soon! I also bought Thinking in C++ just because I was so impressed with Thinking in Java George Laframboise, LightWorx Technology Consulting, Inc I wrote to you earlier about my favorable impressions regarding your Thinking in C++ (a book that stands prominently on my shelf here at work) And today I’ve been able to delve into Java with your e-book in my virtual hand, and I must say (in my best Chevy Chase from “Modern Problems”) “I like it!” Very informative and explanatory, without reading like a dry textbook You cover the most important yet the least covered concepts of Java development: the whys Sean Brady Your examples are clear and easy to understand You took care of many important details of Java that can’t be found easily in the weak Java documentation And you don’t waste the reader’s time with the basic facts a programmer already knows Kai Engert, Innovative Software, Germany I’m a great fan of your Thinking in C++ and have recommended it to associates As I go through the electronic version of your Java book, I’m finding that you’ve retained the same high level of writing Thank you! Peter R Neuwald VERY well-written Java book I think you’ve done a GREAT job on it As the leader of a Chicago-area Java special interest group, I’ve favorably mentioned your book and website several times at our recent meetings I would like to use Thinking in Java as the basis for a part of each monthly SIG meeting, in which we review and discuss each chapter in succession Mark Ertes I really appreciate your work and your book is good I recommend it here to our users and Ph.D students Hugues Leroy // Irisa-Inria Rennes France, Head of Scientific Computing and Industrial Tranfert OK, I’ve only read about 40 pages of Thinking in Java, but I’ve already found it to be the most clearlywritten and presented programming book I’ve come across and I’m a writer, myself, so I am probably a little critical I have Thinking in C++ on order and can’t wait to crack it – I’m fairly new to programming and am hitting learning curves head-on everywhere So this is just a quick note to say thanks for your excellent work I had begun to burn a little low on enthusiasm from slogging through the mucky, murky prose of most computer books – even ones that came with glowing recommendations I feel a whole lot better now Glenn Becker, Educational Theatre Association Thank you for making your wonderful book available I have found it immensely useful in finally understanding what I experienced as confusing in Java and C++ Reading your book has been very satisfying Felix Bizaoui, Twin Oaks Industries, Louisa, Va I must congratulate you on an excellent book I decided to have a look at Thinking in Java based on my experience with Thinking in C++, and I was not disappointed Jaco van der Merwe, Software Specialist, DataFusion Systems Ltd, Stellenbosch, South Africa This has to be one of the best Java books I’ve seen E.F Pritchard, Senior Software Engineer, Cambridge Animation Systems Ltd., United Kingdom Your book makes all the other Java books I’ve read or flipped through seem doubly useless and insulting Brett g Porter, Senior Programmer, Art & Logic I have been reading your book for a week or two and compared to the books I have read earlier on Java, your book seems to have given me a great start I have recommended this book to lot of my friends and they have rated it excellent Please accept my congratulations for coming out with an excellent book Rama Krishna Bhupathi, Software Engineer, TCSI Corporation, San Jose Just wanted to say what a “brilliant” piece of work your book is I’ve been using it as a major reference for in-house Java work I find that the table of contents is just right for quickly locating the section that is required It’s also nice to see a book that is not just a rehash of the API nor treats the programmer like a dummy Grant Sayer, Java Components Group Leader, Ceedata Systems Pty Ltd, Australia Wow! A readable, in-depth Java book There are a lot of poor (and admittedly a couple of good) Java books out there, but from what I’ve seen yours is definitely one of the best John Root, Web Developer, Department of Social Security, London I’ve *just* started Thinking in Java I expect it to be very good because I really liked Thinking in C++ (which I read as an experienced C++ programmer, trying to stay ahead of the curve) I’m somewhat less experienced in Java, but expect to be very satisfied You are a wonderful author Kevin K Lewis, Technologist, ObjectSpace, Inc I think it’s a great book I learned all I know about Java from this book Thank you for making it available for free over the Internet If you wouldn’t have I’d know nothing about Java at all But the best thing is that your book isn’t a commercial brochure for Java It also shows the bad sides of Java YOU have done a great job here Frederik Fix, Belgium I have been hooked to your books all the time A couple of years ago, when I wanted to start with C++, it was C++ Inside & Out which took me around the fascinating world of C++ It helped me in getting better opportunities in life Now, in pursuit of more knowledge and when I wanted to learn Java, I bumped into Thinking in Java – No doubts in my mind as to whether I need some other book Just fantastic It is more like rediscovering myself as I get along with the book It is just a month since I started with Java, and heartfelt thanks to you, I am understanding it better now Anand Kumar S - Software Engineer – Computervision, India Your book stands out as an excellent general introduction Peter Robinson, University of Cambridge Computer Laboratory It’s by far the best material I have come across to help me learn Java and I just want you to know how lucky I feel to have found it THANKS! Chuck Peterson, Product Leader, Internet Product Line, IVIS International The book is great It’s the third book on Java I’ve started and I’m about two-thirds of the way through it now I plan to finish this one I found out about it because it is used in some internal classes at Lucent Technologies and a friend told me the book was on the Net Good work Jerry Nowlin, MTS, Lucent Technologies Of the six or so Java books I’ve accumulated to date, your Thinking in Java is by far the best and clearest Michael Van Waas, Ph.D., President, TMR Associates I just want to say thanks for Thinking in Java What a wonderful book you’ve made here! Not to mention downloadable for free! As a student I find your books invaluable (I have a copy of C++ Inside Out, another great book about C++), because they not only teach me the how-to, but also the whys, which are of course very important in building a strong foundation in languages such as C++ or Java I have quite a lot of friends here who love programming just as I do, and I’ve told them about your books They think it’s great! Thanks again! By the way, I’m Indonesian and I live in Java Ray Frederick Djajadinata, Student at Trisakti University, Jakarta The mere fact that you have made this work free over the Net puts me into shock I thought I’d let you know how much I appreciate and respect what you’re doing Shane LeBouthillier, Computer Engineering student, University of Alberta, Canada I have to tell you how much I look forward to reading your monthly column As a newbie to the world of object oriented programming, I appreciate the time and thoughtfulness that you give to even the most elementary topic I have downloaded your book, but you can bet that I will purchase the hard copy when it is published Thanks for all of your help Dan Cashmer, B C Ziegler & Co Just want to congratulate you on a job well done First I stumbled upon the PDF version of Thinking in Java Even before I finished reading it, I ran to the store and found Thinking in C++ Now, I have been in the computer business for over eight years, as a consultant, software engineer, teacher/trainer, and recently as self-employed, so I’d like to think that I have seen enough (not “have seen it all,” mind you, but enough) However, these books cause my girlfriend to call me a ”geek.” Not that I have anything against the concept - it is just that I thought this phase was well beyond me But I find myself truly enjoying both books, like no other computer book I have touched or bought so far Excellent writing style, very nice introduction of every new topic, and lots of wisdom in the books Well done Simon Goland, simonsez@smartt.com, Simon Says Consulting, Inc I must say that your Thinking in Java is great! That is exactly the kind of documentation I was looking for Especially the sections about good and poor software design using Java 1.1 Dirk Duehr, Lexikon Verlag, Bertelsmann AG, Germany Thank you for writing two great books (Thinking in C++, Thinking in Java) You have helped me immensely in my progression to object oriented programming Donald Lawson, DCL Enterprises Thank you for taking the time to write a really helpful book on Java If teaching makes you understand something, by now you must be pretty pleased with yourself Dominic Turner, GEAC Support It’s the best Java book I have ever read - and I read some Jean-Yves MENGANT, Chief Software Architect NAT-SYSTEM, Paris, France Thinking in Java gives the best coverage and explanation Very easy to read, and I mean the code fragments as well Ron Chan, Ph.D., Expert Choice, Inc., Pittsburgh PA Your book is great I have read lots of programming books and your book still adds insights to programming in my mind Ningjian Wang, Information System Engineer, The Vanguard Group Thinking in Java is an excellent and readable book I recommend it to all my students Dr Paul Gorman, Department of Computer Science, University of Otago, Dunedin, New Zealand You make it possible for the proverbial free lunch to exist, not just a soup kitchen type of lunch but a gourmet delight for those who appreciate good software and books about it Jose Suriol, Scylax Corporation Thanks for the opportunity of watching this book grow into a masterpiece! IT IS THE BEST book on the subject that I’ve read or browsed Jeff Lapchinsky, Programmer, Net Results Technologies Your book is concise, accessible and a joy to read Keith Ritchie, Java Research & Development Team, KL Group Inc It truly is the best book I’ve read on Java! Daniel Eng The best book I have seen on Java! Rich Hoffarth, Senior Architect, West Group Thank you for a wonderful book I’m having a lot of fun going through the chapters Fred Trimble, Actium Corporation You have mastered the art of slowly and successfully making us grasp the details You make learning VERY easy and satisfying Thank you for a truly wonderful tutorial Rajesh Rau, Software Consultant Thinking in Java rocks the free world! Miko O’Sullivan, President, Idocs Inc About Thinking in C++: Best Book! Winner of the 1995 Software Development Magazine Jolt Award! “This book is a tremendous achievement You owe it to yourself to have a copy on your shelf The chapter on iostreams is the most comprehensive and understandable treatment of that subject I’ve seen to date.” Al Stevens Contributing Editor, Doctor Dobbs Journal “Eckel’s book is the only one to so clearly explain how to rethink program construction for object orientation That the book is also an excellent tutorial on the ins and outs of C++ is an added bonus.” Andrew Binstock Editor, Unix Review “Bruce continues to amaze me with his insight into C++, and Thinking in C++ is his best collection of ideas yet If you want clear answers to difficult questions about C++, buy this outstanding book.” Gary Entsminger Author, The Tao of Objects “Thinking in C++ patiently and methodically explores the issues of when and how to use inlines, references, operator overloading, inheritance, and dynamic objects, as well as advanced topics such as the proper use of templates, exceptions and multiple inheritance The entire effort is woven in a fabric that includes Eckel’s own philosophy of object and program design A must for every C++ developer’s bookshelf, Thinking in C++ is the one C++ book you must have if you’re doing serious development with C++.” Richard Hale Shaw Contributing Editor, PC Magazine Thinking in Java Bruce Eckel President, MindView Inc Prentice Hall PTR Upper Saddle River, New Jersey 07458 http://www.phptr.com Library of Congress Cataloging-in-Publication Data Eckel, Bruce Thinking in Java / Bruce Eckel p cm Includes index ISBN 0-13-659723-8 Java (Computer program language) I Title QA76.73.J38E25 1998 005.13'3 dc21 97-52713 CIP Editorial/Production Supervision: Craig Little Acquisitions Editor: Jeffrey Pepper Manufacturing Manager: Alexis R Heydt Marketing Manager: Miles Williams Cover Design Director: Jerry Votta Cover Design: Daniel Will-Harris Interior Design: Daniel Will-Harris, www.will-harris.com © 1998 by Prentice Hall PTR Prentice-Hall Inc A Simon & Schuster Company Upper Saddle River, NJ 07458 The information in this book is distributed on an “as is” basis, without warranty While every precaution has been taken in the preparation of this book, neither the author nor the publisher shall have any liability to any person or entitle with respect to any liability, loss or damage caused or alleged to be caused directly or indirectly by instructions contained in this book or by the computer software or hardware products described herein All rights reserved No part of this book may be reproduced, in any form or by any means, without permission in writing from the publisher Prentice Hall books are widely used by corporations and government agencies for training, marketing, and resale The publisher offers discounts on this book when ordered in bulk quantities For more information, contact the Corporate Sales Department at 800-382-3419, fax: 201-236-7141, email: {HYPERLINK "mailto:corpsales@prenhall.com"} or write: Corporate Sales Department, Prentice Hall PTR, One Lake Street, Upper Saddle River, New Jersey 07458 Java is a registered trademark of Sun Microsystems, Inc Windows 95 and Windows NT are trademarks of Microsoft Corporation All other product names and company names mentioned herein are the property of their respective owners Printed in the United States of America 10 ISBN 0-13-659723-8 Prentice-Hall International (UK) Limited, London Prentice-Hall of Australia Pty Limited, Sydney Prentice-Hall Canada Inc., Toronto Prentice-Hall Hispanoamericana, S.A., Mexico Prentice-Hall of India Private Limited, New Delhi Prentice-Hall of Japan, Inc., Tokyo Simon & Schuster Asia Pte Ltd., Singapore Editora Prentice-Hall Brasil, Ltda., Rio de Janeiro Check www.BruceEckel.com for in-depth details and the date and Java Seminar Multimedia CD Bruce Eckel’s Hands-Onlocation of the next Hands-On Java Seminar It’s like coming to the seminar! • Based onAvailable at http://www.BruceEckel.com this book •• • • • •• • Taught by slides and synchronized Audio audio for all the Overhead Bruce Eckel Personal attention fromitBruce Eckel the lectures! lectures: just Just play to see and hear and hisset of lectures are indexed so you can rapidly locate the Entire seminar assistants Includes in-class subject you’re interested in discussion of the programming exercises Also: Intermediate/Advanced seminars also offered in Special screen-formatted electronic version of “Thinking Hundreds have already enjoyed this seminar –contents Java” book with hyperlinked index and table of see the Web site for their testimonials Dedication To the person who, even now, is creating the next great computer language restrain your impulses to optimize early because you may forgo many useful programming techniques, resulting in code that’s harder to understand, riskier, and requires more effort to maintain Locating the bottleneck Three approaches to locating the performance-critical part of a program are: Install your own instrumentation “Profile” code by inserting explicit timing: long start = System.currentTimeMillis(); // Operation to be timed goes here long time = System.currentTimeMillis() - start; Have an infrequently-used method print cumulative times out to the console window with System.out.println( ) Since the compiler will ignore it when false, a static final boolean switch can turn the timing on and off so the code can efficiently be left in place in released code, ready for emergency use at any time Even when more sophisticated profiling is available, this is a convenient way to time a specific task or operation System.currentTimeMillis( ) returns time in 1/1000ths of a second However, some systems with time resolution less than a millisecond (such as a Windows PC) need to repeat an operation n times and divide the total time by n to get accurate estimates JDK profiling [2] The JDK comes with a built-in profiler that keeps track of the time spent in each routine and writes the information to a file Unfortunately, the JDK profilers have uneven performance JDK 1.1.1 works, but subsequent releases have had various instabilities To run the profiler, use the -prof option when invoking the unoptimized versions of the Java interpreter, for example: java_g -prof myClass Or with an applet: java_g -prof sun.applet.AppletViewer applet.html The profiler output is not particularly easy to decipher In fact, in JDK 1.0 it truncates the method names to 30 characters, so it might not be possible to distinguish between some methods However, if your platform does support the -prof option, either Vladimir Bulatov’s HyperProf [3] or Greg White’s ProfileViewer [4] will help interpret the results Special tools The best way to keep up with the exploding field of performance optimization tools is through a Web site such as Jonathan Hardwick’s Tools for Optimizing Java [5] at http://www.cs.cmu.edu/~jch/java/tools.html { PAGE } Thinking in Java www.BruceEckel.com Tips for measuring performance ϖ♦ Since profiling uses clock time, make every effort to remove other processes during the measurement ϖ♦ Always time the code before and after making changes to verify that, at least on the test platform, your changes improved the program (Jon Bentley mentioned that some of his most logical changes actually slowed the program down.) ϖ♦ Try to make each timing test under identical conditions ϖ♦ If possible, contrive a test that doesn’t rely on any user input to avoid variations in user response that can cause the results to fluctuate Speedup techniques Now that the critical region has been isolated, you can apply two types of optimizations: generic techniques and those specific to Java Generic approaches An effective generic speedup is to redefine the program in a more practical way For example, in Programming Pearls [14], Bentley describes Doug McIlroy’s representation of the English language with a novel data depiction that enabled him to produce a remarkably fast, compact spelling checker In addition, choosing a better algorithm will probably give a bigger performance gain than any other approach, particularly as the size of the data set increases For more of these generic approaches, see the general book listings [12-19] at the end of this appendix Language dependent approaches To put things in perspective, it’s useful to look at the time it takes to perform various operations So that the results are relatively independent of the computer being used, they have been normalized by dividing by the time it takes to make a local assignment Operation Example Local assignment Instance assignment int increment byte increment short increment float increment double increment Empty loop Ternary expression Math call Array assignment long increment Method call i = n; this.i = n; i++; b++; s++; f++; d++; while(true) n++; (x> (or any power of 2) Why Multiple inheritance of interfaces prevents some optimizations Time (above) shows an instance integer assignment is 1.2 local integer assignments, but an array assignment is 2.7 local integer assignments Each new object takes 980 local assignments See Reusing Objects (below), Van Wyk [12] p 87 and Bentley[15] p 81 Uses faster hardware instructions Specific situations The cost of Strings: The String concatenation operator + looks innocent but involves a lot of work The compiler can efficiently concatenate constant strings, but a variable string requires considerable processing For example, if s and t are String variables: System.out.println("heading" + s + "trailer" + t); this requires a new StringBuffer, appending arguments, and converting the result back to a String with toString( ) This costs both space and time If you’re appending more than one String, consider using a StringBuffer directly, especially if you can repeatedly reuse it in a loop Preventing the creation of a new StringBuffer on each iteration saves the object creation time of 980 seen earlier Using substring( ) and the other String methods is usually an improvement When feasible, character arrays are even faster Also notice that StringTokenizer is costly because of synchronization Synchronization: In the JDK interpreter, calling a synchronized method is typically 10 times slower than calling an unsynchronized method With JIT compilers, this performance gap has increased to 50 to 100 { PAGE } Thinking in Java www.BruceEckel.com times (notice the timing above shows it to be 97 times slower) Avoid synchronized methods if you can – if you can’t, synchronizing on methods rather than on code blocks is slightly faster Reusing objects: It takes a long time to create an object (the timing above shows 980 assignment times for a new Object, and 3100 assignment times for a small new array), so it’s often worth saving and updating the fields of an old object instead of creating a new object For example, rather than creating a new Font object in your paint( ) method, you can declare it an instance object, initialize it once, and then just update it when necessary in paint( ) See also Bentley, Programming Pearls p 81 [15] Exceptions: You should only throw exceptions in abnormal situations, which are usually cases in which performance is not an issue since the program has run into a problem that it doesn’t normally expect When optimizing, combine small try-catch blocks, which thwart compiler optimization by breaking the code into small independent sections On the other hand, be careful of sacrificing the robustness of your code by over-zealous removal of exception handling Hashing: The standard Hashtable class in Java 1.0 and 1.1 requires casting and costly synchronization (570 assignment times) Furthermore, the early JDK library doesn’t deliberately choose prime number table sizes Finally, a hashing function should be designed for the particular characteristics of the keys actually used For all these reasons, the generic Hashtable can be improved by designing a hash class that fits a particular application Note that the HashMap in the Java 1.2 collections library has much greater flexibility and isn’t automatically synchronized Method inlining: Java compilers can inline a method only if it is final, private, or static, and in some cases it must have no local variables If your code spends a lot of time calling a method that has none of these modifiers, consider writing a version that is final I/O: Use buffers wherever possible, otherwise you can end up doing I/O a single byte at a time Note that the JDK 1.0 I/O classes use a lot of synchronization, so you might get better performance by using a single “bulk” call such as readFully( ) and then interpreting the data yourself Also notice that the Java 1.1 “reader” and “writer” classes were designed for improved performance Casts and instanceof: Casts take from to 200 assignment times The more costly ones require travel up the inheritance hierarchy Other costly operations lose and restore capabilities of the lower level constructs Graphics: Use clipping to reduce the amount of work done in repaint( ), double buffering to improve perceived speed, and image strips or compression to speed downloading times Animation in Java Applets from JavaWorld and Performing Animation from Sun are two good tutorials Remember to use high-level primitives; it’s much faster to call drawPolygon( ) on a bunch of points than looping with drawLine( ) If you must draw a one-pixel-wide line, drawLine(x,y,x,y) is faster than fillRect(x,y,1,1) Using API classes: Use classes from the Java API when they offer native machine performance that you can’t match using Java For example, arrayCopy( ) is much faster than using a loop to copy an array of any significant size Replacing API classes: Sometimes API classes more than you need, with a corresponding increase in execution time For these you can write specialized versions that less but run faster For example, one application that needed a container to store many arrays was speeded by replacing the original Vector with a faster dynamic array of objects Other suggestions ϖ♦ Move repeated constant calculations out of a critical loop, for example, computing buffer.length for a constant-size buffer Appendix D: Performance { PAGE } ϖ♦ static final constants can help the compiler optimize the program ϖ♦ Unroll fixed length loops ϖ♦ Use javac’s optimization option, -O, which optimizes compiled code by inlining static, final, and private methods Note that your classes may get larger in size (JDK 1.1 or later only – earlier versions might not perform byte verification) Newer just-in-time (JIT) compilers will dramatically speed the code ϖ♦ Count down to zero whenever possible – this uses a special JVM byte code References Performance tools [1] MicroBenchmark running on Pentium Pro (200Mh), Netscape 3.0, JDK 1.1.4 (see reference [5] below) [2] Sun’s Java document page on the JDK Java interpreter http://java.sun.com/products/JDK/tools/win32/java.html [3] Vladimir Bulatov’s HyperProf http://www.physics.orst.edu/~bulatov/HyperProf [4] Greg White’s ProfileViewer http://www.inetmi.com/~gwhi/ProfileViewer/ProfileViewer.html Web sites [5] The premiere online references for optimizing Java code are Jonathan Hardwick’s Java Optimization site at http://www.cs.cmu.edu/~jch/java/optimization.html, “Tools for Optimizing Java” at http://www.cs.cmu.edu/~jch/java/tools.html, and “Java Microbenchmarks” (with a quick 45 second measurement benchmark) at http://www.cs.cmu.edu/~jch/java/benchmarks.html Articles [6] Make Java fast: Optimize! How to get the greatest performance out of your code through low-level optimizations in Java by Doug Bell http://www.javaworld.com/javaworld/jw-04-1997/jw-04-optimize.html, complete with an extensive annotated measurement Benchmark applet [7] Java Optimization Resources http://www.cs.cmu.edu/~jch/java/resources.html [8] Optimizing Java for Speed http://www.cs.cmu.edu/~jch/java/speed.html [9] An Empirical Study of FORTRAN Programs by Donald Knuth, 1971, Software – Practice and Experience, Volume p 105-33 [10] Building High-Performance Applications and Servers in Java: An Experiential Study, by Jimmy Nguyen, Michael Fraenkel, Richard Redpath, Binh Q Nguyen, and Sandeep K Singhal; IBM Software Solutions, IBM T.J Watson Research Center http://www.ibm.com/java/education/javahipr.html { PAGE } Thinking in Java www.BruceEckel.com Java specific books [11] Advanced Java, Idioms, Pitfalls, Styles, and Programming Tips, by Chris Laffra, Prentice Hall, 1997 (Java 1.0) Chapter Sections 11-20 General books [12] Data Structures and C Programs by Christopher J Van Wyk, Addison-Wesley, 1988 [13] Writing Efficient Programs by Jon Bentley, Prentice Hall, 1982, especially p 110 and p 145-151 [14] More Programming Pearls by Jon Bentley Association for Computing Machinery, February 1988 [15] Programming Pearls by Jon Bentley, Addison-Wesley 1989 Part II addresses generic performance enhancements [16] Code Complete: A Practical Handbook of Software Construction by Steve McConnell, Microsoft Press 1993, Chapter [17] Object-Oriented System Development by Champeaux, Lea, and Faure, Chapter 25 [18] The Art of Programming by Donald Knuth, Volume Fundamental Algorithms 3rd Edition, 1997; Volume 2, Seminumerical Algorithms 3rd Edition; Volume Sorting and Searching 2nd Edition, AddisonWesley The definitive encyclopedia of algorithms [19] Algorithms in C: Fundamentals, Data Structures, Sorting, Searching by Robert Sedgewick, 3rd Edition, Addison-Wesley 1997 The author is an apprentice of Knuth’s This is one of seven editions devoted to several languages and contains timely, somewhat simpler treatments of algorithms Appendix D: Performance { PAGE } E: A bit about garbage collection It’s hard to believe that Java could possibly be as fast or faster than C++ This assertion has yet to be proven to my satisfaction However, I’ve begun to see that many of my doubts about speed come from early implementations that were not particularly efficient so there was no model at which to point to explain how Java could be fast Part of the way I’ve thought about speed has come from being cloistered with the C++ model C++ is very focused on everything happening statically, at compile time, so that the run-time image of the program is small and fast C++ is also based directly on the C model, primarily for backwards compatibility, but sometimes simply because it worked a particular way in C so it was the easiest approach in C++ One of the most important cases is the way memory is managed in C and C++, and this has to with one of my more fundamental assertions about why Java must be slow: in Java, all objects must be created on the heap In C++, creating objects on the stack is fast because when you enter a particular scope the stack pointer is moved down once to allocate storage for all the stack-based objects created in that scope, and when you leave the scope (after all the local destructors have been called) the stack pointer is moved up once However, creating heap objects in C++ is typically much slower because it’s based on the C concept of a heap as a big pool of memory that (and this is essential) must be recycled When you call delete in C++ the released memory leaves a hole in the heap, so when you call new, the storage allocation mechanism must go seeking to try to fit the storage for your object into any existing holes in the heap or else you’ll rapidly run out of heap storage Searching for available pieces of memory is the reason that allocating heap storage has such a performance impact in C++, so it’s far faster to create stack-based objects Again, because so much of C++ is based on doing everything at compile-time, this makes sense But in Java there are certain places where things happen more dynamically and it changes the model When it { PAGE } comes to creating objects, it turns out that the garbage collector can have a significant impact on increasing the speed of object creation This might sound a bit odd at first – that storage release affects storage allocation – but it’s the way some JVMs work and it means that allocating storage for heap objects in Java can be nearly as fast as creating storage on the stack in C++ You can think of the C++ heap (and a slow implementation of a Java heap) as a yard where each object stakes out its own piece of turf This real estate can become abandoned sometime later and must be reused In some JVMs, the Java heap is quite different; it’s more like a conveyor belt that moves forward every time you allocate a new object This means that object storage allocation is remarkably rapid The “heap pointer” is simply moved forward into virgin territory, so it’s effectively the same as C++’s stack allocation (Of course, there’s a little extra overhead for bookkeeping but it’s nothing like searching for storage.) Now you might observe that the heap isn’t in fact a conveyor belt, and if you treat it that way you’ll eventually start paging memory a lot (which is a big performance hit) and later run out The trick is that the garbage collector steps in and while it collects the garbage it compacts all the objects in the heap so that you’ve effectively moved the “heap pointer” closer to the beginning of the conveyor belt and further away from a page fault The garbage collector rearranges things and makes it possible for the high-speed, infinite-free-heap model to be used while allocating storage To understand how this works, you need to get a little better idea of the way the different garbage collector (GC) schemes work A simple but slow GC technique is reference counting This means that each object contains a reference counter, and every time a handle is attached to an object the reference count is increased Every time a handle goes out of scope or is set to null, the reference count is decreased Thus, managing reference counts is a small but constant overhead that happens throughout the lifetime of your program The garbage collector moves through the entire list of objects and when it finds one with a reference count of zero it releases that storage The one drawback is that if objects circularly refer to each other they can have non-zero reference counts while still being garbage Locating such self-referential groups requires significant extra work for the garbage collector Reference counting is commonly used to explain one kind of garbage collection but it doesn’t seem to be used in any JVM implementations In faster schemes, garbage collection is not based on reference counting Instead, it is based on the idea that any non-dead object must ultimately be traceable back to a handle that lives either on the stack or in static storage The chain might go through several layers of objects Thus, if you start in the stack and the static storage area and walk through all the handles you’ll find all the live objects For each handle that you find, you must trace into the object that it points to and then follow all the handles in that object, tracing into the objects they point to, etc., until you’ve moved through the entire web that originated with the handle on the stack or in static storage Each object that you move through must still be alive Note that there is no problem with detached self-referential groups – these are simply not found, and are therefore automatically garbage In the approach described here, the JVM uses an adaptive garbage-collection scheme, and what it does with the live objects that it locates depends on the variant currently being used One of these variants is stopand-copy This means that, for reasons that will become apparent, the program is first stopped (this is not a background collection scheme) Then, each live object that is found is copied from one heap to another, leaving behind all the garbage In addition, as the objects are copied into the new heap they are packed endto-end, thus compacting the new heap (and allowing new storage to simply be reeled off the end as previously described) Of course, when an object is moved from one place to another, all handles that point at (reference) that object must be changed The handle that comes from tracing to the object from the heap or the static storage area can be changed right away, but there can be other handles pointing to this object that will be { PAGE } Thinking in Java www.BruceEckel.com encountered later during the “walk.” These are fixed up as they are found (you could imagine a hash table mapping old addresses to new ones) There are two issues that make copy collectors inefficient The first is the idea that you have two heaps and you slosh all the memory back and forth between these two separate heaps, maintaining twice as much memory as you actually need Some JVMs deal with this by allocating the heap in chunks as needed and simply copying from one chunk to another The second issue is the copying Once your program becomes stable it might be generating little or no garbage Despite that, a copy collector will still copy all the memory from one place to another, which is wasteful To prevent this, some JVMs detect that no new garbage is being generated and switch to a different scheme (this is the “adaptive” part) This other scheme is called mark and sweep, and it’s what Sun’s JVM uses all the time For general use mark and sweep is fairly slow, but when you know you’re generating little or no garbage it’s fast Mark and sweep follows the same logic of starting from the stack and static storage and tracing through all the handles to find live objects However, each time it finds a live object that object is marked by setting a flag in it, but the object isn’t collected yet Only when the marking process is finished does the sweep occur During the sweep, the dead objects are released However, no copying happens, so if the collector chooses to compact a fragmented heap it does so by shuffling objects around The “stop-and-copy” refers to the idea that this type of garbage collection is not done in the background; instead, the program is stopped while the GC occurs In the Sun literature you’ll find many references to garbage collection as a low-priority background process, but it turns out that this was a theoretical experiment that didn’t work out In practice, the Sun garbage collector is run when memory gets low In addition, mark-and-sweep requires that the program be stopped As previously mentioned, in the JVM described here memory is allocated in big blocks If you allocate a large object, it gets its own block Strict stop-and-copy requires copying every live object from the source heap to a new heap before you could free the old one, which translates to lots of memory With blocks, the GC can typically use dead blocks to copy objects to as it collects Each block has a generation count to keep track of whether it’s alive In the normal case, only the blocks created since the last GC are compacted; all other blocks get their generation count bumped if they have been referenced from somewhere This handles the normal case of lots of short-lived temporary objects Periodically, a full sweep is made – large objects are still not copied (just get their generation count bumped) and blocks containing small objects are copied and compacted The JVM monitors the efficiency of GC and if it becomes a waste of time because all objects are long-lived then it switches to mark-and-sweep Similarly, the JVM keeps track of how successful mark-and-sweep is, and if the heap starts to become fragmented it switches back to stop-and-copy This is where the “adaptive” part comes in, so you end up with a mouthful: “adaptive generational stop-and-copy mark-and-sweep.” There are a number of additional speedups possible in a JVM An especially important one involves the operation of the loader and Just-In-Time (JIT) compiler When a class must be loaded (typically, the first time you want to create an object of that class), the class file is located and the byte codes for that class are brought into memory At this point, one approach is to simply JIT all the code, but this has two drawbacks: it takes a little more time, which, compounded throughout the life of the program, can add up; and it increases the size of the executable (byte codes are significantly more compact than expanded JIT code) and this might cause paging, which definitely slows down a program An alternative approach is lazy evaluation, which means that the code is not JIT compiled until necessary Thus, code that never gets executed might never get JIT compiled Because JVMs are external to browsers, you might expect that you could benefit from the speedups of some JVMs while using any browser Unfortunately, JVMs don’t currently interoperate with different Appendix E: A Bit about Garbage Collection { PAGE } browsers To get the benefits of a particular JVM, you must either use the browser with that JVM built in or run standalone Java applications { PAGE } Thinking in Java www.BruceEckel.com F: Recommended reading Java in a Nutshell: A Desktop Quick Reference, 2nd Edition, by David Flanagan, O’Reilly & Assoc 1997 A compact summary of the online documentation of Java 1.1 Personally, I prefer to browse the docs online, especially since they change so often However, many folks still like printed documentation and this fits the bill; it also provides more discussion than the online documents The Java Class Libraries: An Annotated Reference, by Patrick Chan and Rosanna Lee, Addison-Wesley 1997 What the online reference should have been: enough description to make it usable One of the technical reviewers for Thinking in Java said, “If I had only one Java book, this would be it (well, in addition to yours, of course).” I’m not as thrilled with it as he is It’s big, it’s expensive, and the quality of the examples doesn’t satisfy me But it’s a place to look when you’re stuck and it seems to have more depth (and sheer size) than Java in a Nutshell Java Network Programming, by Elliote Rusty Harold, O’Reilly 1997 I didn’t begin to understand Java networking until I found this book I also find his Web site, Café au Lait, to be a stimulating, opinionated, and up-to-date perspective on Java developments, unencumbered by allegiances to any vendors His almost daily updating keeps up with fast-changing news about Java See http://sunsite.unc.edu/javafaq/ Core Java, 3nd Edition, by Cornell & Horstmann, Prentice-Hall 1997 A good place to go for questions you can’t find the answers to in Thinking in Java Note: the Java 1.1 revision is Core Java 1.1 Volume – Fundamentals & Core Java 1.1 Volume – Advanced Features JDBC Database Access with Java, by Hamilton, Cattell & Fisher (Addison-Wesley, 1997) If you know nothing about SQL and databases, this is a nice, gentle introduction It also contains some of the details as well as an “annotated reference” to the API (again, what the online reference should have been) The drawback, as with all books in The Java Series (“The ONLY Books Authorized by JavaSoft”) is that it’s been whitewashed so that it says only wonderful things about Java – you won’t find out about any dark corners in this series { PAGE } Java Programming with CORBA Andreas Vogel & Keith Duddy (John Wiley & Sons, 1997) A serious treatment of the subject with code examples for the three main Java ORBs (Visibroker, Orbix, Joe) Design Patterns, by Gamma, Helm, Johnson & Vlissides (Addison-Wesley 1995) The seminal book that started the patterns movement in programming UML Tookit, by Hans-Erik Eriksson & Magnus Penker, (John Wiley & Sons, 1997) Explains UML and how to use it, and has a case study in Java An accompanying CD-ROM contains the Java code and a cut-down version of Rational Rose An excellent introduction to UML and how to use it to build a real system Practical Algorithms for Programmers, by Binstock & Rex (Addison-Wesley 1995) The algorithms are in C, so they’re fairly easy to translate into Java Each algorithm is thoroughly explained { PAGE } Thinking in Java www.BruceEckel.com Check www.BruceEckel.com for in-depth details and the date and location of the next Hands-On Java Seminar • Based on this book • Taught by Bruce Eckel • Personal attention from Bruce Eckel and his seminar assistants • Includes in-class programming exercises • Also: Intermediate/Advanced seminars also offered • Hundreds have already enjoyed this seminar – see the Web site for their testimonials Huu Thanh Design 2002 Bruce Eckel’s Hands-On Java Seminar Multimedia CD It’s like coming to the seminar! Available at http://www.BruceEckel.com • Overhead slides and synchronized Audio audio for all the lectures: just Just play it to see and hear the lectures! • Entire set of lectures are indexed so you can rapidly locate the discussion of the subject you’re interested in • Special screen-formatted electronic version of “Thinking in Java” book with hyperlinked index and table of contents Index { PAGE } ... Thinking in Java Even before I finished reading it, I ran to the store and found Thinking in C++ Now, I have been in the computer business for over eight years, as a consultant, software engineer,... have read lots of programming books and your book still adds insights to programming in my mind Ningjian Wang, Information System Engineer, The Vanguard Group Thinking in Java is an excellent and... 07458 http://www.phptr.com Library of Congress Cataloging -in- Publication Data Eckel, Bruce Thinking in Java / Bruce Eckel p cm Includes index ISBN 0-13-659723-8 Java (Computer program language)

Ngày đăng: 18/10/2013, 01:15

TỪ KHÓA LIÊN QUAN