More Java Pitfalls 50 New Time-Saving Solutions and Workarounds phần 1 ppt

48 188 0
More Java Pitfalls 50 New Time-Saving Solutions and Workarounds phần 1 ppt

Đ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

Simpo PDF Merge and Split Unregistered Version - http://www.simpopdf.com More Java ™ Pitfalls 50 New Time-Saving Solutions and Workarounds Simpo PDF Merge and Split Unregistered Version - http://www.simpopdf.com Simpo PDF Merge and Split Unregistered Version - http://www.simpopdf.com Michael C. Daconta Kevin T. Smith Donald Avondolio W. Clay Richardson More Java ™ Pitfalls 50 New Time-Saving Solutions and Workarounds Simpo PDF Merge and Split Unregistered Version - http://www.simpopdf.com Publisher: Joe Wikert Executive Editor: Robert M. Elliott Assistant Developmental Editor: Emilie Herman Managing Editor: Micheline Frederick New Media Editor: Angela Denny Text Design & Composition: Wiley Composition Services This book is printed on acid-free paper. ∞ Copyright  2003 by Michael C. Daconta, Kevin T. Smith, Donald Avondolio, and W. Clay Richardson. All rights reserved. Published by Wiley Publishing, Inc., Indianapolis, Indiana Published simultaneously in Canada No part of this publication may be reproduced, stored in a retrieval system, or transmitted in any form or by any means, electronic, mechanical, photocopying, recording, scanning, or otherwise, except as permitted under Section 107 or 108 of the 1976 United States Copyright Act, without either the prior written permission of the Publisher, or authorization through payment of the appropriate per-copy fee to the Copyright Clearance Center, Inc., 222 Rose- wood Drive, Danvers, MA 01923, (978) 750-8400, fax (978) 646-8700. Requests to the Pub- lisher for permission should be addressed to the Legal Department, Wiley Publishing, Inc., 10475 Crosspoint Blvd., Indianapolis, IN 46256, (317) 572-3447, fax (317) 572-4447, E-mail: permcoordinator@wiley.com. Limit of Liability/Disclaimer of Warranty: While the publisher and author have used their best efforts in preparing this book, they make no representations or warranties with respect to the accuracy or completeness of the contents of this book and specifically disclaim any implied warranties of merchantability or fitness for a particular purpose. No warranty may be created or extended by sales representatives or written sales materials. The advice and strategies contained herein may not be suitable for your situation. You should consult with a professional where appropriate. Neither the publisher nor author shall be liable for any loss of profit or any other commercial damages, including but not limited to special, inci- dental, consequential, or other damages. Wiley, the Wiley Publishing logo and related trade dress are trademarks or registered trade- marks of Wiley Publishing, Inc., in the United States and other countries, and may not be used without written permission. Java is a trademark or registered trademark of Sun Microsystems, Inc All other trademarks are the property of their respective owners. Wiley Publishing, Inc., is not associated with any product or vendor mentioned in this book. For general information on our other products and services please contact our Customer Care Department within the United States at (800) 762-2974, outside the United States at (317) 572-3993 or fax (317) 572-4002. Wiley also publishes its books in a variety of electronic formats. Some content that appears in print may not be available in electronic books. Library of Congress Cataloging-in-Publication Data: ISBN: 0-471-23751-5 Printed in the United States of America 10 9 8 7 6 5 4 3 2 1 Simpo PDF Merge and Split Unregistered Version - http://www.simpopdf.com This book is dedicated to the memory of Edsger W. Dijkstra who said, “I mean, if 10 years from now, when you are doing something quick and dirty, you suddenly visualize that I am looking over your shoulders and say to yourself, ‘Dijkstra would not have liked this’, well that would be enough immortality for me.” We humbly disagree: 10 years of Dijkstra is just not long enough; may he happily haunt our consciousness for 10 10 years. Such an increase is more befitting his stature. Simpo PDF Merge and Split Unregistered Version - http://www.simpopdf.com Simpo PDF Merge and Split Unregistered Version - http://www.simpopdf.com Introduction xi Acknowledgments xvii Part One The Client Tier 1 Item 1: When Runtime.exec() Won’t 4 Item 2: NIO Performance and Pitfalls 17 Canonical File Copy 20 Little-Endian Byte Operations 21 Non-Blocking Server IO 26 Item 3: I Prefer Not to Use Properties 34 Item 4: When Information Hiding Hides Too Much 39 Item 5: Avoiding Granularity Pitfalls In java.util.logging 44 Item 6: When Implementations of Standard APIs Collide 53 Item 7: My Assertions are Not Gratuitous! 59 How to Use Assertions 59 Item 8: The Wrong Way to Search a DOM 66 Item 9: The Saving-a-DOM Dilemma 73 Item 10: Mouse Button Portability 80 Item 11: Apache Ant and Lifecycle Management 88 Item 12: JUnit: Unit Testing Made Simple 100 Contents vii Simpo PDF Merge and Split Unregistered Version - http://www.simpopdf.com Item 13: The Failure to Execute 108 Deploying Java Applications 109 The Java Extension Mechanism 110 Sealed Packages 111 Security 112 Item 14: What Do You Collect? 112 Item 15: Avoiding Singleton Pitfalls 117 When Multiple Singletons in Your VM Happen 119 When Singletons are Used as Global Variables, or Become Non-Singletons 120 Item 16: When setSize() Won’t Work 122 Item 17: When Posting to a URL Won’t 126 Connecting via HTTP with the java.net Classes 126 An Alternative Open Source HTTP Client 137 Item 18: Effective String Tokenizing 140 Item 19: JLayered Pane Pitfalls 146 Item 20: When File.renameTo() Won’t 151 Item 21: Use Iteration over Enumeration 157 Item 22: J2ME Performance and Pitfalls 162 Part Two The Web Tier 199 Item 23: Cache, It’s Money 200 Item 24: JSP Design Errors 208 Request/Response Paradigm 208 Maintaining State 209 JSP the Old Way 210 JSP Development with Beans (Model 1 Architecture) 214 JSP Development in the Model 2 Architecture 220 Item 25: When Servlet HttpSessions Collide 220 Item 26: When Applets Go Bad 227 Item 27: Transactional LDAP—Don’t Make that Commitment 235 Item 28: Problems with Filters 244 Item 29: Some Direction about JSP Reuse and Content Delivery 255 Item 30: Form Validation Using Regular Expressions 261 viii Contents Simpo PDF Merge and Split Unregistered Version - http://www.simpopdf.com Item 31: Instance Variables in Servlets 269 Item 32: Design Flaws with Creating Database Connections within Servlets 279 Item 33: Attempting to Use Both Output Mechanisms in Servlets 291 Item 34: The Mysterious File Protocol 297 Item 35: Reading Files from Servlets 302 Web Application Deployment Descriptors 308 Item 36: Too Many Submits 312 Preventing Multiple Submits 314 Handling Multiple Submits 316 Part Three The Enterprise Tier 327 Item 37: J2EE Architecture Considerations 329 Item 38: Design Strategies for Eliminating Network Bottleneck Pitfalls 335 A Scenario 336 General Design Considerations 336 EJB Design Considerations 340 Item 39: I’ll Take the Local 341 Item 40: Image Obsession 348 Item 41: The Problem with Multiple Concurrent Result Sets 353 Item 42: Generating Primary Keys for EJB 359 A Simple Scenario 359 A “Client Control” Approach 360 The Singleton Approach 362 The Networked Singleton Approach 363 An Application Server-Specific Approach 363 Database Autogeneration Approaches 363 Other Approaches 364 Item 43: The Stateful Stateless Session Bean 365 Message-Driven Beans 366 Entity Bean 366 Stateful Session Bean 368 Stateless Session Bean 368 Item 44: The Unprepared PreparedStatement 372 Contents ix Simpo PDF Merge and Split Unregistered Version - http://www.simpopdf.com [...]... 16 : } catch (Throwable t) 17 : { 18 : t.printStackTrace(); 19 : } 20: } 21: } Listing 1. 1 BadExecJavac .java A run of BadExecJavac produces the following: E:\classes\org\javapitfalls\item1 >java org.javapitfalls.item1.BadExecJavac java. lang.IllegalThreadStateException: process has not exited at java. lang.Win32Process.exitValue(Native Method) at BadExecJavac.main(BadExecJavac .java: 13 ) Æ The program failed... process to complete In Listing 1. 2, the program again attempts to exec the program javac.exe and then waits for the Merge and Split Unregistered Version - http://www.simpopdf.com external process to complete 01: 02: 03: 04: 05: 06: 07: 08: 09: 10 : 11 : 12 : 13 : 14 : 15 : 16 : 17 : 18 : 19 : 20: 21: package org.javapitfalls.item1; import java. util.*; import java. io.*; public class BadExecJavac2 { public static void... 05: 06: 07: 08: 09: 10 : 11 : 12 : 13 : 14 : 15 : 16 : 17 : 18 : 19 : 20: 21: 22: 23: 24: 25: 26: 27: 28: 29: package org.javapitfalls.item1; import java. util.*; import java. io.*; public class MediocreExecJavac { public static void main(String args[]) { try { Runtime rt = Runtime.getRuntime(); Process proc = rt.exec(“javac”); InputStream stderr = proc.getErrorStream(); InputStreamReader isr = new InputStreamReader(stderr);... org.javapitfalls.item1; 02: 03: import java. util.*; and Split Unregistered Version - http://www.simpopdf.com 04: import java. io.*; 05: 06: class StreamGobbler extends Thread 07: { 08: InputStream is; 09: String type; 10 : 11 : StreamGobbler(InputStream is, String type) 12 : { 13 : this.is = is; 14 : this.type = type; 15 : } 16 : 17 : public void run() 18 : { 19 : try 20: { 21: InputStreamReader isr = new InputStreamReader(is);... (APIs), and better alternatives Here are some highlights of pitfalls in each area Performance has long been the bane of client-side Java The first book, Java Pitfalls: Time-Saving Solutions and Workarounds to Improve Programs, had numerous pitfalls on performance, and many other books and Web sites have come out on Java performance tuning This part has two pitfalls on performance: 1 2 Part 1 NIO Performance... the Java compiler (javac.exe) Listing 1. 1 is a program to do that 1 This pitfall was first printed by JavaWorld (www.javaworld.com) in “When Runtime.exec() won’t”, December 2000 (http://www.javaworld.com/javaworld/jw -12 -2000/jw -12 29-traps.html?) and is reprinted here with permission The pitfall has been updated from reader feedback Simpo PDF Merge When Runtime.exec() Won’t 01: package org.javapitfalls.item1;... org.javapitfalls.item1; 02: 03: import java. util.*; and Split Unregistered Version - http://www.simpopdf.com 04: import java. io.*; 05: 06: public class BadExecJavac 07: { 08: public static void main(String args[]) 09: { 10 : try 11 : { 12 : Runtime rt = Runtime.getRuntime(); 13 : Process proc = rt.exec(“javac”); 14 : int exitVal = proc.exitValue(); 15 : System.out.println(“Process exitValue: “ + exitVal); 16 : } catch... which when run produces the following: E:\classes\org\javapitfalls\item1 >java org.javapitfalls.item1.BadExecWinDir java. io.IOException: CreateProcess: dir error=2 at java. lang.Win32Process.create(Native Method) at java. lang.Win32Process.(Unknown Source) at java. lang.Runtime.execInternal(Native Method) at BadExecWinDir.main(BadExecWinDir .java: 12 ) Æ As stated earlier, the error value of 2 means file... outputGobbler.start(); 81: 82: // any error??? 83: int exitVal = proc.waitFor(); 84: System.out.println(“ExitValue: “ + exitVal); 85: 86: } catch (Throwable t) 87: { 88: t.printStackTrace(); 89: } 90: } 91: } Listing 1. 4 (continued) Simpo PDF Merge When Runtime.exec() Won’t Running GoodWindowsExec with the dir command produces: E:\classes\org\javapitfalls\item1 >java org.javapitfalls.item1.GoodWindowsExec “dir * .java and. .. os; 11 : 12 : StreamGobbler(InputStream is, String type) 13 : { 14 : this(is, type, null); 15 : } 16 : 17 : StreamGobbler(InputStream is, String type, OutputStream redirect) 18 : { 19 : this.is = is; 20: this.type = type; 21: this.os = redirect; 22: } 23: 24: public void run() 25: { 26: try 27: { 28: PrintWriter pw = null; 29: if (os != null) 30: pw = new PrintWriter(os); 31: 32: InputStreamReader isr = new . http://www.simpopdf.com Item 13 : The Failure to Execute 10 8 Deploying Java Applications 10 9 The Java Extension Mechanism 11 0 Sealed Packages 11 1 Security 11 2 Item 14 : What Do You Collect? 11 2 Item 15 : Avoiding. Simpo PDF Merge and Split Unregistered Version - http://www.simpopdf.com More Java ™ Pitfalls 50 New Time-Saving Solutions and Workarounds Simpo PDF Merge and Split Unregistered Version. Merge and Split Unregistered Version - http://www.simpopdf.com Michael C. Daconta Kevin T. Smith Donald Avondolio W. Clay Richardson More Java ™ Pitfalls 50 New Time-Saving Solutions and Workarounds Simpo

Ngày đăng: 13/08/2014, 12:21

Mục lục

  • Item 2: NIO Performance and Pitfalls

    • Canonical File Copy

    • Item 3: I Prefer Not to Use Properties

    • Item 4: When Information Hiding Hides Too Much

    • Item 7: My Assertions Are Not Gratuitous!

      • How to Use Assertions

      • Item 8: The Wrong Way to Search a DOM

      • Item 9: The Saving-a-DOM Dilemma

      • Item 10: Mouse Button Portability

      • Item 11: Apache Ant and Lifecycle Management

      • Item 12: JUnit: Unit Testing Made Simple

      • Item 13: The Failure to Execute

        • Deploying Java Applications

        • The Java Extension Mechanism

        • Item 14: What Do You Collect?

        • Item 15: Avoiding Singleton Pitfalls

          • When Multiple Singletons in Your VM Happen

          • Item 16: When setSize() Won’t Work

          • An Alternative Open Source HTTP Client

          • Item 18: Effective String Tokenizing

          • Item 19: JLayered Pane Pitfalls

          • Item 21: Use Iteration over Enumeration

          • Item 22: J2ME Performance and Pitfalls

          • Item 23: Cache, It’s Money

Tài liệu cùng người dùng

  • Đang cập nhật ...

Tài liệu liên quan