⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 ch1.htm

📁 JAVA Developing Professional JavaApplets
💻 HTM
📖 第 1 页 / 共 5 页
字号:
Since it is written in software, however, it is portable. Allthat's needed to take Java code compiled on one platform and runit on another is to provide a Java interpreter and runtime environment.The runtime system is written in an easily portable fashion. Onceyou have this system, everything becomes easy. You don't evenhave to port the Java compiler-it is written in Java!<P>Another advantage of the Java interpreter is that it improvessoftware development by eliminating the link phase of the developmentprocess. You can go straight from compiling your code to executingit. Linking actually occurs at runtime through mechanisms discussedin the section &quot;Java as a Secure Environment.&quot;<P>A couple of higher-level features also improve Java's portability.The Abstract Window Toolkit (or AWT) is constructed to be a visualinterface that is portable across platforms. This way your appletswill look good regardless of the underlying interface. They willhave the proper &quot;look and feel&quot; on Microsoft Windows,the Macintosh, or X-Windows. Although not a portability issuein the strict sense, Java stores characters by using the 16-bitUnicode format as opposed to the 8-bit ASCII standard. Unicodeis used if you need to support international character sets. Sincethe Internet is an international network, this consideration isimportant.<H3><A NAME="JavaasHighPerformance">Java as High Performance</A></H3><P>One of the reasons why Java's portable solution is such a coupis that interpreted platforms have generally been very slow. Oftentheir performance is so poor that systems based on these interpretershave been unusable. Java's bytecode system, however, providesa &quot;lean and mean&quot; interpreted solution. It isn't basedon multimegabyte executable &quot;image&quot; files. Rather, theruntime system works with small binary <I>class files</I> compiledto Java virtual machine code. These files typically have a sizeof only a few kilobytes.<P>However, Java offers more than just the byte-code system to gethigh performance. Since the byte-code system is at a low level,it can be easily converted at runtime to the native platform.Just-in-time Java compilers will be out in the near future toallow this. Another performance enhancement is a by-product ofanother Java feature. When a class is brought into memory at runtime,it runs through a verification process as part of the Java securitymechanism (discussed in the section &quot;Java as a Secure Environment&quot;).This process not only guarantees that the code you are loadingis secure, but the end result is code that requires less runtimechecks. These checks, which otherwise would hurt performance,now don't need to be executed. For example, the runtime systemdoes not have to check for stack overflows on verified code.<P>One of the key features that Java offers to improve performanceis <I>multithreading.</I> Most interactive applications are characterizedby large periods of time during which the user pauses betweenactions to decide what to do next. In traditional single-threadedenvironments, the application may sit idle during such periods.In multithreaded environments, however, the application can performother tasks during these types of delays or at any other time.This is critical for network applications, which can take longperiods of time to load files. Wouldn't it be more efficient ifyou could read the current page of text while the next page isbeing downloaded? Multithreading also greatly improves the usabilityof multimedia applications. For example, you need to be able tointeract with your system while a sound or a movie is playing.Multithreading is useful for even more down-to-earth things, suchas running a background thread that spell checks your documentas you are typing in words.<P>You can use Java's easy-to-use multithreading environment to performall kinds of optimizations to your program. In fact, the designersof Java have taken great pains to make sure it's easy to writemultithreaded programs. Historically, writing multithreaded applicationshas been quite difficult-a key reason they have appeared infrequently.Furthermore, Java uses threads to improve its own performance.The garbage collector that takes care of your memory managementconcerns runs in the background as a low-priority thread. So evenwhen your program is doing nothing, the garbage collector couldbe busy optimizing memory!<P>There are some other interesting things Java does to guaranteegood performance. As stated earlier, Java is &quot;objects allthe way down.&quot; In some object-oriented systems, primitivessuch as integers and floating point numbers are implemented onlyas objects. So to perform an operation such as adding two numbers,you actually have to call an object method. If you are doing someserious number crunching, this will absolutely kill your performance.Java has an intermediate solution to resolve the dilemma betweenhaving good performance and being a pure object-oriented system.It implements &quot;type wrappers&quot; to take primitives, suchas numbers, and make them appear as objects. This way, methods-suchas converting numbers to strings-can be performed by using theobject-oriented method style. However, if you need to work withraw data types, you can use the primitive formats to produce suchthings as CPU-intensive images like fractals. Java can even beused to create the computation-hungry Mandelbrot set. It's ratherremarkable that Java can do this; if you don't believe it can,then see <A HREF="ch14.htm" >Chapter 14</A>, &quot;Advanced ImageProcessing.&quot;<P>If you really need that final push to your performance, Java canlink to executable code written in a low-level native languagesuch as C. Java code that does this is said to use <I>native methods</I>.This technique can also be used to implement platform-specificfeatures. However, using native methods is not without its drawbacks;it will probably compromise the portability of your code. Fortunately,Java performance is generally good enough that you don't needto bring in native methods very often.<P>Finally, it is important to remember that the Java community isconstantly working on techniques to improve performance but notcompromise all the other features of Java, such as portability.The just-in-time compilers that will be out later this year areamong the most impressive of such optimizations.<H3><A NAME="JavaintheWorldofDistributedComputin">Java in the Worldof Distributed Computing</A></H3><P>Much of what has been discussed so far makes Java well suitedfor network computing. In particular, the lightweight nature ofthe binary class files makes it possible to download Java codewithout serious performance hits. Multithreading is also criticalfor latency-laden network operations; your applet can downloadcode and resources in the background while the end user is decidingthe next action to take. Portability frees you from knowing howyour applet will run and what it will look like on your potentialclient's unknown platform.<P>Another feature of Java that makes it excellent for distributedcomputing is that it's <I>dynamic</I>. Since there is no linkingphase after compilation, the resolution of references is put offuntil runtime. Java also does not calculate the layout of objectsin memory until they are used at runtime. Consequently, if youadd a new method to one class, you don't have to recompile anotherclass that uses the class but not the method. In C++, you areconstantly having to recompile multiple classes because one is&quot;dependent&quot; on the other-this is known as the &quot;fragilesuperclass problem.&quot; In its typical efficient manner, Javasolves the superclass problem while taking care of other issues.Since the Java dynamic system removes difficulties caused by unnecessarydependencies, it's easy to download a special subclass to handlea specific situation without worrying about &quot;linking&quot;problems.<P>The Java development package also gives you a variety of goodcommunication constructs. The message-passing mechanism of itsobjects can be used to let two different applets communicate;this is known as &quot;inter-applet communication.&quot; Sockets,pipes, and thread synchronization constructs also provide othereasy-to-use communication mechanisms. In short, Java providesall the basics for creating distributed systems.<H3><A NAME="JavaasaSecureEnvironment">Java as a Secure Environment</A></H3><P>Although distributed systems are extremely powerful, they openthe door to a range of security problems, which are particularlyserious on a vast open network like the Internet. For normal datatransmission, you have to be concerned with someone eavesdroppingon your information as it passes through the network. If you havea server on the Internet, you have to worry about someone breakingin and wreaking havoc on your internal network. And if you'redownloading applications from the net, you have to worry aboutit causing damage to your host system.<P>The kind of damage a poorly written application could inflicton your host spans a range of extremes. On one hand, a poorlywritten application can misuse the resources of your system, takingresources you might need elsewhere. For example, a C program thatmismanages memory can simply take memory that another one of yourapplications needs. If the program is really bad, it can causeyour system to lock up. Fortunately, it's usually easy to recoverfrom such problems. However, the other end of the extreme is notquite so innocent. A malicious program can attack some of themost critical resources of your computer, such as your hard disk,causing damage less easily fixed. If the program is a virus, itcan be even more pernicious. It can lie in wait for weeks or evenmonths, then one day pounce on your computer and connecting network,causing hours or even days of lost work time. If this attack camefrom an application that you ran from the World Wide Web, youwould probably be reluctant to use the Web again. Consequently,bad Web programs not only threaten your system, but the viabilityof the Web as a whole.<P>The designers of Java know just how important security is. Forthis reason, they built a multi-layered security system whosepresence is felt throughout Java. This security model consistsof four main layers:<UL><LI><FONT COLOR=#000000>The </FONT><B>language</B> itself is designedto be safe. A strict <B>compiler</B> prevents generating bytecodesthat don't completely follow extensive safety rules.<LI><FONT COLOR=#000000>A runtime </FONT><B>bytecode verifier</B>that inspects class bytecodes as they are loaded into the system.Since code loaded at runtime has already passed through the compilationstage, Java cannot know that it hasn't been produced by a maliciousor weak compiler that does not follow all the language's safetyrules.<LI><FONT COLOR=#000000>Once code has been verified, it needsto be loaded into a runtime namespace. This is performed by amodule called the </FONT><B>Class</B> <B>Loader</B>, representedby a like-named class. Java has a different namespace dependingon whether the loaded class came from a local file system or acrossa network. These separate namespaces prevent a class from passingitself off as a new low-level class. Therefore, it can't do suchthings as replacing the existing Security Manager (discussed brieflyin the next bulleted item).<LI><FONT COLOR=#000000>The final layer performs checks on thecode as it's being executed. This layer makes sure the code doesnot violate any security restrictions defined for the currentenvironment; it's generally represented by a module called the</FONT><B>Security Manager</B>, which corresponds to a Java classof a similar name. An applet that can delete a file on your computeris an example of something that falls under the auspices of theSecurity Manager. The workings of Security Managers can vary ondifferent environments. Extremely conservative Java-enabled browsers,such as Netscape Navigator, actually prevent applets from readingor writing to your local file system altogether. The HotJava browser,on the other hand, can be configured to authorize file operationsmore flexibly.</UL><P>Figure 1.1 gives an overview of the lifetime of Java code as ittravels through the layers of security. Those modules relatedto security are set off in boldface.<P>Since security is such a critical part of Java, it is worth takinga moment to look at it in greater detail. In doing so, you willget some greater insight into the inner workings of Java.<P><A HREF="f1-1.gif" >Figure 1.1 : <I>The Java life</I>-cycle in relationship to its security layers.</A><H4>First Security Layer: The Language and Compiler</H4><P>You have already seen a couple of reasons why Java is a securelanguage. A key ingredient here is removing pointers from Java.Without pointers, a bad or malicious program cannot invade thememory space of other applications. This removes a major sourceof attack for viruses. For example, a threatening program cannotuse Java as a launching pad to directly attack your operatingsystem kernel. Furthermore, the absence of pointers makes theJava applet itself more secure and reliable. An applet won't crashbecause of a &quot;dangling pointer,&quot; as is often the casein C and C++.<P>Another security feature of the language is its class access mechanism.Classes can control the kinds of access other classes have totheir methods and variables. There are four access modifiers,ranging from <TT>public</TT>, whichindicates availability to all classes, to <TT>private</TT>,which makes a method or variable accessible only from within theclass where it's defined. These modifiers can make your classmore secure by denying other classes access to critical behavior.For example, if you have a class that manages critical data ina private method, another class cannot invoke that method to changethe data. Access modifiers will be discussed in more detail inthe next section.<P>The compiler uses very strict checking to ensure adherence tothese and other Java language constructs. Java is a strongly typedlanguage, so runtime bugs aren't introduced because of freelycasting one type of object to another. A language like C is notoriousfor its loose casting mechanism. A pointer to a structure canbe fairly easily cast into a long integer, and vice versa. Whensuch casting is done incorrectly, pernicious and difficult-to-findbugs can be introduced, but this kind of casting is eliminatedin Java. All casts must be explicit, and those that don't followthe semantics of the language are disallowed. Because the compiler

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -