1 / 41

Advanced Programming

Advanced Programming. Rabie A. Ramadan Rabie@rabieramadan.org Lecture 5. Item 13: Use objects to manage resources. class Investment { … }; Investment * createInvestment (); // factory function, caller must delete pointer // when finished using it void f() {

marla
Download Presentation

Advanced Programming

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. Advanced Programming Rabie A. Ramadan Rabie@rabieramadan.org Lecture 5

  2. Item 13: Use objects to manage resources.

  3. class Investment { … }; Investment *createInvestment(); // factory function, caller must delete pointer // when finished using it void f() { Investment *pInv = createInvestment(); … delete pInv; } Q1: what might goes wrong with the following code: Looks OK, but what if premature return? OR, exception thrown? Even if correct at first, what happens as code is maintained?

  4. class Investment { … }; Investment *createInvestment(); // factory function, caller must delete pointer // when finished using it void f() { Investment *pInv = createInvestment(); … delete pInv; } Q2: how can I solve this problem ?

  5. A solution.. • Put the resource returned by createInvestment inside an object whose destructor will release the resource when control leaves f. • std::auto_ptr is a smart pointer whose destructor automatically calls delete on what it points to void f() { std::auto_ptr<Investment> pInv(createInvestment()); … // use pInv as before } call to factory function will delete pInv via auto_ptr’s destructor

  6. There should never be more than one auto_ptr pointing to an object, or the object will be deleted more than once. Copying an auto_ptr sets it to NULL, so copying pointer has sole ownership. std::auto_ptr<Investment> pInv1(createInvestment()); std::auto_ptr<Investment> pInv2(pInv1); // pInv1 now NULL pInv1 = pInv2; // pInv2 now NULL Q3: what is the problem with auto pointers ?

  7. Sometimes pointers must have “normal” copying behavior (e.g., in container classes) Use reference-counting smart pointer (RCSP). Keeps track of how many objects point to resource, deletes it when nobody points to it. Similar to garbage collection, but can’t break cycles. void f() { std::tr1::shared_ptr<Investment> pInv1(createInvestment()); // count=1 std::tr1::shared_ptr<Investment> pInv2(pInv1); // both now point to same object, count = 2 pInv1 = pInv2; // still point to same object, count = 2 } Q4: what are the other alternatives ? pointers destroyed at end, object count will be 0 so it will be destroyed.

  8. auto_ptr and tr1::shared_ptr use delete, not delete [] in their destructors Bad idea: std::auto_ptr<std::string> aps(new std::string[10]); std::tr1::shared_ptr<int> spi(new int[1024]); Boost library has classes for dealing with arrays. You can also create your own resource-managing class. Q5: why it is not recommended to use these pointers with arrays?

  9. Item 14: Think carefully about copying behavior in resource-managing classes.

  10. Copying behavior in resource-managing classes Sometimes you need to use your own recourse manger class for pointers . Not all pointers kept in heap Q6: what is the main idea behind item 14?

  11. Copying such pointer Q7: what is the problem you should handle if you use your own resource manger class ?

  12. Prohibit copying. Might not make sense to have a copy – why would you have a copy of a Lock? Reference-count the underlying resource. Hold the resource until the last object using it has been destroyed. tr1::shared_ptr does this. BUT, shared_ptr deletes resource when reference count is 0, may not be what you want. Can specify “deleter” as second parameter to shared_ptr constructor. Q8: what are the possible solution ?

  13. Copy the underlying resource. Only purpose of resource-managing class is to ensure resource gets deleted. Makes a deep copy. Transfer ownership of the underlying resource. Used by auto_ptr in Item #13. Q8

  14. Chapter 10Applets

  15. Q9: What is the main structure of an Applet’s class ?

  16. public class MyApplet extends java.applet.Applet { ... /** The no-arg constructor is called by the browser when the Web page containing this applet is initially loaded, or reloaded */ public MyApplet() { ... } /** Called by the browser after the applet is loaded */ public void init() { ... } /** Called by the browser after the init() method, or every time the Web page is visited */ public void start() { ... } /** Called by the browser when the page containing this applet becomes inactive */ public void stop() { ... } /** Called by the browser when the Web browser exits */ public void destroy() { ... } /** Other methods if necessary... */ }

  17. When the applet is loaded, the Web browser creates an instance of the applet by invoking the applet’s no-arg constructor. The browser uses the init, start, stop, and destroymethods to control the applet. By default, these methods do nothing. To perform specific functions, they need to be modified in the user's applet so that the browser can call your code properly. The Applet Class

  18. Q10: Draw a flowchart showing how the browser deals with applets ?

  19. Invoked when the applet is first loaded and again if the applet is reloaded. A subclass of Applet should override this method if the subclass has an initialization to perform. The functions usually implemented in this method include creating new threads, loading images, setting up user-interface components, and getting string parameter values from the <applet> tag in the HTML page. Q11: When the init()Method is called ?

  20. Invoked after the init() method is executed; also called whenever the applet becomes active again after a period of inactivity (for example, when the user returns to the page containing the applet after surfing other Web pages). A subclass of Applet overrides this method if it has any operation that needs to be performed whenever the Web page containing the applet is visited. An applet with animation, for example, might use the start method to resume animation. Q12: When the start()Method is called ?

  21. The opposite of the start() method, which is called when the user moves back to the page containing the applet; the stop() method is invoked when the user moves off the page. A subclass of Applet overrides this method if it has any operation that needs to be performed each time the Web page containing the applet is no longer visible. When the user leaves the page, any threads the applet has started but not completed will continue to run. You should override the stopmethod to suspend the running threads so that the applet does not take up system resources when it is inactive. Q13: When the stop()Method is called ?

  22. Invoked when the browser exits normally to inform the applet that it is no longer needed and that it should release any resources it has allocated. A subclass of Applet overrides this method if it has any operation that needs to be performed before it is destroyed. Usually, you won't need to override this method unless you wish to release specific resources, such as threads that the applet created. Q14: When the destroy()Method is called ?

  23. Q15: The Applet class is an AWT class and is not designed to work with Swing components. To use Swing components in Java applets, it is necessary to create a Java applet that extends ………… , which is a subclass of ………….

  24. The Applet class is an AWT class and is not designed to work with Swing components. To use Swing components in Java applets, it is necessary to create a Java applet that extends javax.swing.JApplet, which is a subclass of java.applet.Applet. JApplet inherits all the methods from the Applet class. In addition, it provides support for laying out Swing components. Q15:

  25. Q16: Is there anything wrong with these two applets ?

  26. Q16 Run Applet Viewer

  27. Always extends theJAppletclass, which is a subclass of Applet for Swing components. Overrideinit(), start(), stop(), anddestroy() if necessary. By default, these methods are empty. Add your own methods and data if necessary. Applets are always embedded in an HTML page. Summary

  28. <applet code = "DisplayMessage.class" width = 200 height = 50> <param name=MESSAGE value="Welcome to Java"> <param name=X value=20> <param name=Y value=20> alt="You must have a Java-enabled browser to view the applet" </applet> Q17: what is the purpose of this html file?

  29. <applet code=classfilename.class width=applet_viewing_width_in_pixels height=applet_viewing_height_in_pixels [archive= location of archivefile] [codebase=applet_url] [vspace=vertical_margin] [hspace=horizontal_margin] [align=applet_alignment] [alt=alternative_text] > <param name=param_name1 value=param_value1> </applet> The<applet>HTML Tag

  30. Similarities Since JFrame and JApplet both are subclasses of the Container class, all the user interface components, layout managers and event-handling features are the same for both classes. Q18: What are the similarities between Applets and Applications ?

  31. Differences Applications are invoked from the static main method by the Java interpreter, and applets are run by the Web browser. The Web browser creates an instance of the applet using the applet’s no-arg constructor and controls and executes the applet through the init, start, stop, and destroymethods. Applets have security restrictions Web browser creates graphical environment for applets, GUI applications are placed in a frame. Q19: What are the differences between Applets and Applications ?

  32. Applets are not allowed to read from, or write to, the file system of the computer viewing the applets. Applets are not allowed to run any programs on the browser’s computer. Applets are not allowed to establish connections between the user’s computer and another computer except with the server wherethe applets are stored. Q20: What are the Security Restrictions on Applets?

  33. Due to security restrictions, applets cannot access local files. How can an applet load resource files for image and audio? Use URL class instead of absolute location Q21:

  34. ImageIconimageIcon = new ImageIcon("c:\\book\\image\\us.gif"); jlbl.setIcon(imageIcon); This approach suffers a problem. The file location is fixed since it uses the absolute file path on Window. Thus, the program cannot run on other platforms and cannot run as applet. Example : Class metaObject = this.getClass(); URL url = metaObject.getResource("image/us.gif"); You can now create an ImageIcon using ImageIconimageIcon = newImageIcon(url); Q22: What is wrong with this code ?

  35. Class class = this.getClass(); URL url = class.getResource("beep.au"); AudioClip audioClip = Applet.newAudioClip(url); Q23: How to run an audio clip in an applet ?

  36. Java archive file can be used to group all the project files in a compressed file for deployment. The Java archive file format (JAR) is based on the popular ZIP file format. Pack200 tool Q24: What is JAR?

  37. This single file can be deployed on an end-user’s machine as an application. It also can be downloaded to a browser in a single HTTP transaction, rather than opening a new connection for each piece. This greatly simplifies application deployment and improves the speed with which an applet can be loaded onto a web page and begin functioning. Q25: Why should I use JAR ?

  38. jar -cf TicTacToe.jar TicTacToe.classTicTacToe$Cell.class The -c option is for creating a new archive file, The -f option specifies the archive file’s name. Creating JAR

  39. The manifest is a special file that contains information about the files packaged in a JAR file. For instance, the manifest file in TicTacToe.jar contains the following information: Manifest-Version: 1.0 Name: TicTacToe.class Java-Bean: True Name: TioTacToe$Cell.class Java-Bean: True Q26 : What is the function of Manifest File

  40. To run TicTacToe as an applet, modify the <APPLET> tag in the HTML file to include an ARCHIVE attribute. The ARCHIVE attribute specifies the archive file in which the applet is contained. For example, the HTML file for running TicTacToe can be modified as shown below: <APPLET CODE = "TicTacToe.class" ARCHIVE = "TicTacToe.jar" WIDTH = 400 HEIGHT = 300 HSPACE = 0 VSPACE = 0 ALIGN = Middle > </APPLET> Jar and Applete

  41. Acquire the basic knowledge and essential concepts of Java programming including data types, loops, arrays, classes, inner and outer classes, the concept of Servlets, and Applets programming. Acquire advanced knowledge in C++ programming through learning different advanced skills. Q27: Are we satisfying the following items :

More Related