Review Java Beans

Source: Internet
Author: User

Now that we understand synchronization, we can then look at the Java Beans from another perspective. Whenever you create a bean, you must assume that it will run in a multithreaded environment. This means that:
(1) All public methods of the bean should be synchronized whenever feasible. Of course, this also brings the overhead of "sync" during run time. If you pay special attention to this problem, the methods that do not cause problems in critical areas can be left as "not synchronized", but note that this is usually not very easy to judge. The qualifying approach tends to be small in size (Getcirclesize ()) and/or "tiny" as the case may be. In other words, this method invocation is executed in so few pieces of code that the object cannot be changed during execution. If you set this method to not sync, you may not have a noticeable effect on the execution speed of your program. You may also set all public methods for a bean to synchronized and delete the Synchronized keyword only if the guarantee is particularly necessary and creates a difference.
(2) If a multiple-styling event is given to a series of "listeners" interested in that event, it must be added or removed when moving through the list.

1th is easy to handle, but the 2nd needs to be considered for more things. Let's take the Bangbean.java in our previous chapter for example. In that example, we ignored the Synchronized keyword (which was not introduced at the time) and set the styling to single styling, thus avoiding the problem of multithreading. In the revised version below, we made it work in a multithreaded environment and used multiple styling techniques for events:
 

: Bangbean2.java//You should write your Beans this way so they//can run in a multithreaded environment.
Import java.awt.*;
Import java.awt.event.*;
Import java.util.*;

Import java.io.*;
  public class BangBean2 extends Canvas implements Serializable {private int xm, YM; private int csize = 20;
  Circle size private String Text = "bang!";
  private int fontsize = 48;
  Private Color tcolor = color.red;
  Private vector actionlisteners = new vector ();
    Public BangBean2 () {Addmouselistener (New ML ());
  Addmousemotionlistener (New MM ()); 
  public synchronized int Getcirclesize () {return csize;
  Public synchronized void setcirclesize (int newsize) {csize = newsize; 
  Public synchronized String Getbangtext () {return text;
  Public synchronized void Setbangtext (String newtext) {text = NewText; 
  public synchronized int Getfontsize () {return fontsize; Public synchronized void setfontsize (int newsize) {
    FontSize = newsize; 
  Public synchronized Color GetTextColor () {return tcolor;
  Public synchronized void SetTextColor (Color newcolor) {tcolor = Newcolor;
    public void Paint (Graphics g) {G.setcolor (color.black);
  G.drawoval (XM-CSIZE/2, YM-CSIZE/2, CSize, csize); }//This is a multicast listener, which are//more typically used than the unicast//approach taken in Bangbean.ja
  Va:public synchronized void addActionListener (ActionListener l) {actionlisteners.addelement (L);
  Public synchronized void Removeactionlistener (ActionListener l) {actionlisteners.removeelement (L); }//Notice This isn ' t synchronized:public void Notifylisteners () {ActionEvent a = new ActionEvent (bangbea
    N2.this, actionevent.action_performed, NULL);
    Vector LV = null; Make a copy of the vector in case someone//adds a listener while we ' RE//calling Listeners:synchronize D (This) {LV = (Vector) actionlisteners.clone (); }//Call all the listener methods:for (int i = 0; i < lv.size (); i++) {ActionListener Al = (Ac
      Tionlistener) Lv.elementat (i);
    Al.actionperformed (a);
      Class ML extends Mouseadapter {public void mousepressed (MouseEvent e) {Graphics g = getgraphics ();
      G.setcolor (TColor);
      G.setfont (New Font ("Timesroman", Font.Bold, FontSize));
      int width = g.getfontmetrics (). Stringwidth (text);
      g.DrawString (Text, (GetSize (). Width-width)/2, GetSize (). HEIGHT/2);
      G.dispose ();
    Notifylisteners ();
      } class MM extends Mousemotionadapter {public void mousemoved (MouseEvent e) {xm = E.getx ();
      ym = E.gety ();
    Repaint ();
    }//testing the Bangbean2:public static void main (string[] args) {BangBean2 bb = new BangBean2 (); Bb.addactionlistener (new ActionListener () {public voidactionperformed (ActionEvent e) {System.out.println ("ActionEvent" + e);
    }
    }); Bb.addactionlistener (new ActionListener () {public void actionperformed (ActionEvent e) {System.out.println ("
      BangBean2 action ");
    }
    }); Bb.addactionlistener (new ActionListener () {public void actionperformed (ActionEvent e) {System.out.println ("
      More action ");
    }
    });
    Frame aframe = new Frame ("BangBean2 Test");
      Aframe.addwindowlistener (New Windowadapter () {public void windowclosing (WindowEvent e) {system.exit (0);
    }
    });
    Aframe.add (BB, borderlayout.center);
    Aframe.setsize (300,300);
  Aframe.setvisible (TRUE); }
} ///:~

It's easy to add synchronized to a method. But note that in addActionListener () and Removeactionlistener (), ActionListener is now added and removed from a vector, so you can use as many as you wish.
We note that the Notifylisteners () method is not set to "sync." You can emit a call to this method from multiple threads. In addition, calls to addActionListener () and Removeactionlistener () may also be emitted halfway through the notifylisteners () call. This obviously creates a problem because it negates the vector actionlisteners. To alleviate this problem, we "clone" vectors in a synchronized clause and negate the cloning. This allows the vector to be manipulated without affecting the notifylisteners ().
The paint () method is also not set to "sync." It is much more difficult to decide whether to synchronize the overload method than to simply add your own method. In this case, whether paint () is "synchronized", it seems to work properly. But the issues that must be considered include:
(1) Does the method modify the state of the "key" variable inside the object? To determine whether a variable is "critical", you must know whether it will be read or set by other threads in the program (in the current situation, reading or setting is almost certainly done through the "sync" method, so you can only check them). In the case of paint (), no changes will occur.
(2) is the method based on the state of these "key" variables? If a "sync" method modifies a variable, and our method uses that variable, it is generally willing to set its own method to "sync". Based on this premise, you can observe that the CSize is modified by the "sync" method, so the paint () should be "synchronized". But here, we can ask: "What would have been the worst thing that could have happened if CSize had changed during the execution of paint?" "If you find that the situation is not too bad and is only temporary, it is best to keep the paint state of the () to avoid the extra overhead of synchronizing method calls."
(3) The third clue to note is whether the paint () base class version is "Synchronized", where it is not synchronized. This is not a very strict parameter, just a "clue". For example, in the present case, a field changed by the synchronization method (good csize) has been synthesized into the paint () formula and may have changed the situation. Note, however, that synchronized cannot inherit-that is, if a method is "synchronized" in the underlying class, it will not automatically enter the "Sync" state in the overloaded version of the derived class.
The test code in TESTBANGBEAN2 has been modified on the basis of the previous chapter, adding an additional "listener" to demonstrate BangBean2 's ability to sculpt.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.