I have a doubt about The Single-Thread Rule

The [url http://java.sun.com/docs/books/tutorial/uiswing/overview/threads.html#rule]Single Thread Rule states:
Rule: Once a Swing component has been realized, all code that might affect or depend on the state of that component should be executed in the event-dispatching thread.
I began to wonder about this because so much code seems to work just fine when it isn't executed in the event dispatching thread. Why are there exceptions? I went looking for some code which acted differently when executed on the event thread than when it was not. I found this
http://forum.java.sun.com/thread.jsp?forum=57&thread=410423&message=1803725#1803725
Now I started wondering why this was the case. What I found was that DefaultCaret adds a document listener to the document of the JTextComponent. In this listener, the insertUpdate() method specifically tests if it is running on the event dispatch thread and if it is, it updates the caret position.public void insertUpdate(DocumentEvent e) {
    if (async || SwingUtilities.isEventDispatchThread()) {
        // ... update the caret position ...
}I then copied the code from DefaultCaret and made a MyCaret. I needed to tweek the code a little bit, but it ran. I removed the event thread test. It worked outside the event thread. There was a small difference in the results though. The textarea did not scroll all the way to the bottom. Almost, but not quite. I didn't test enough to make sure this was the only problem, but there was at least one problem.
Now I started think about why this would be. The thought crossed my mind that the order of the events which were posted to the event queue were probably important. Sun found bugs when components were updated out of the event thread, so they essentially ignored events which weren't on the event thread and created the The Single-Thread Rule.
A few days pass. I'm starting to wonder if Sun could have done a better job making Swing components thread safe. I also don't know that this specific case I found was the rule or the exception to the rule. But without insight into the design philosopy of Swing, I would have to examine all their components and see how they have written them and see if I can come up with a better design. That sound like a lot of work. Especially without getting paid for it.
But wait a second, all you have to do is call the append() method of JTextArea on the event thread. If that is the case, why didn't they write the freakin component that way? Well, I'll try itclass MyTextArea extends JTextArea {
  public MyTextArea(int rows, int columns) { super(rows,columns); }
  public void append(final String text) {
    if (SwingUtilities.isEventDispatchThread()) super.append(text);
    else {
      SwingUtilities.invokeLater(new Runnable() {
        public void run() { myAppend(text); }
  private void myAppend(String text) { super.append(text); }
}I change [url http://forum.java.sun.com/thread.jsp?forum=57&thread=410423&message=1803725#1803725]camickr's code to use a MyTextArea and it works fine without calling from the event thread. I've essentially moved The Single-Thread Rule to the component itself rather than relying on each and every one of the [url http://www.aboutlegacycoding.com/default.htm?AURL=%2FSurveys%2FSurvey6intro%2Easp]2.5 million Java programmers worldwide to use SwingUtilities.invaokeLater().
Now for my question...
Why didn't Sun do this?

Swing is slow enough as it is. Lets not make it slower
just
because dense "programmers" don't know what they are
doing.I agree with you in defending the current model, but aren't you a bit harsh there?!? ;-)
Well, there are a number of not-so-dense programmers that expect such high-level components to be thread-safe. The question is worth asking whether Sun intentionally favor the explicit thread management for performance reasons, or whether this was an oversight.
I'd go for the former (intentional) : indeed any GUI toolkit is inherently thread-based; there is always a distinction between the graphical thread(s) and the application threads - and the programmer always has to manage explicit thread creation to handle long-running event handlers without blocking the event dispatching thread. Extending thread concerns to the updating of components is therefore not a big move.
So it seems fair that a core GUI toolkit does not hide thread issues (though to the best of my knowledge there is no such limitation in updating AWT components), or at least that's what Sun deemed.
An ease-of-use-focused toolkit wrapping the core toolkit for thread-safety can be provided as a third-party product. Though I agree that wrapping the dozens of existing widgets and hundreds of methods is cumbersome - and the lack of such products probably shows it would have a low added value to trained developpers.
Because your way is an extra method call and if
statement, neither of which is necessary if you already know you
are in the correct thread. Now count the number of methods
which will need to be changed (and add up the extra cost).Indeed it's quite common to update several properties of several widgets in one bulk (when user clicks "OK", add a row to the table, change the title of the window, update status bar, re-enable all buttons, change some color,...).
In this case explicit thread management doesn't spare one if but a dozen of redundant ifs!
Note that there could have been if-less ways to cope for thread safety, such as creating a copy of the component's model when a change is made to a component, and switching the model only before paint() is called in the event-dispatching - of course coalescing all changes into the same "updated" model until paint() is called.
But this would trade ease of use for redundant memory consumption, especially for some components with potentially huge models (JTree, JTable, JTextArea,...). And Swing appears to be already quite memory-greedy!

Similar Messages

  • Doubt about the creation MARS rule ??

    Hello,
    My question is the following one: I have a double authentication system (already created) to which a Juniper FW as well as a Cisco ASA 8.0 equipment are related as (Secure Access). This is the process:
    a)      From his pc, the user accesses an authentication website. It is in the FW Juniper (that information is verified in a radiator).
    b)      If the identity is the correct one, the second step would be in the Cisco ASA, in which, to validate, the user has to enter his user LDAP.
    My idea is to register those events (rule) in Cisco MARS in the best/clear way possible. The equipments are already configured to inform to the MARS, and they are already included.
    Thanks in Advance.

    Please clarify what do you intend to accomplist with this rule, the post is not clear.
    Regards
    Farrukh

  • Doubt about the distribution system

    I have a doubt about the distribution system.
    We have made a publication and download it and have it in our iPad. The client does not want tosell or that anyone other than its 15 commercial rest her ipad. How can we host it in those 15ipads?, Do I need any of the subscription programs adobe?
    Thanks!

    function(){return A.apply(null,[this].concat($A(arguments)))}
    function(){return A.apply(null,[this].concat($A(arguments)))}Matthew Laun wrote:
    Yeah... Someone did that yesterday with 70-something users all trying to get the updated folio at once, and it caused server outages. I've got a feeling we may modify the user agreement to limit this. Not saying for sure, just a word of caution.
    Matthew
    I don't understand this reply at all.  Many of us have been using acrobat.com in exactly this fashion, and I've posted about it many times; including a full review:
    http://forums.adobe.com/message/3853106#3853106
    Did Adobe not see this coming? How would you limit the download amount without gutting the functionality?  Would this apply to paid acrobat.com accounts as well?
    I'm about to upgrade my acrobat.com account this week to host more than 1 folio.  You need to clarify what you mean by 'modify the user agreement' ASAP.

  • Doubt about the sizing in the CPH

    Hi gurus!
    I have the following doubt about the sizing in the CPH.  I'm going to implement the CCMS BI CONTENT, i read the Note 979581 - Installing and configuring the CCMS BI Content, but in the document called "IT Performance Reporting Using SAP NetWeaver Business Intelligence" you can see images in this link:
    http://www.servidor-imagenes.com/show-image.php?id=050236bd91654e16c94a559350611dff
    here said how I can calculate the sizing based in Data Record Size per each Metric stored, but in specific,  about the example: 20 systems, 17 CPH metrics. are included SCM, BI, ECC, SOLMAN in this 20 systems? And about the 17 CPH Metrics is talking about ratios? what's mean the CPH metrics?, How can I know what is my CPH metrics?
    I hope can help me
    Best Regards
    Ramon Sanchez

    this theme has been closed on our enterprise

  • Where we can know about the stuck threads without taking thread dump.

    Hi Everyone,
    Where we can View/know about the stuck threads without taking thread dump.
    Thank You

    Hi!
    WebLogic Server diagnoses a thread as stuck if it is continually working (not idle) for a set period of time. You can tune stuck threads in the Weblogic Server.
    You can tune a server’s thread detection behavior by changing the length of time before a thread is diagnosed as stuck, and by changing the frequency with which the server checks for stuck threads.
    It can be configured using below mentioned 2 parameters. These can be configured from Admin console -> Servers ->Configuration > Tuning tab.
    1)Stuck Thread Max Time
    2)Stuck Thread Timer Interval
    Although you can change the criteria WebLogic Server uses to determine whether a thread is stuck, you cannot change the default behavior of setting the “warning” and “critical” health states when all threads in a particular execute queue become stuck.
    There is a parameter "Stuck Thread Count" which can be configured from Console
    (Servers -> Configuration ->Overload -> Stuck Thread count) which helps to transition the Server to FAILED state once the stuck threads reaches the value.
    You can also use "OverloadProtectionMBean" for tuning. In Weblogic Server 9.x and later, it is recommended that you use the "ServerFailureTriggerMBean" in the "OverloadProtectionMBean".The ServerFailureTriggerMBean transitions the server to a FAILED state after the specified number of stuck threads are detected.The OverloadProtectionMBean has options to suspend or shutdown a failed server.
    WebLogic Server checks for stuck threads periodically. If all application threads are stuck, a server instance marks itself failed, if configured to do so, exits. You can configure Node Manager or a third-party high-availability solution to restart the server instance for automatic failure recovery.
    You can configure these actions to occur when not all threads are stuck, but the number of stuck threads have exceeded a configured threshold:
    - Shut down the Work Manager if it has stuck threads. A Work Manager that is shut down will refuse new work and reject existing work in the queue by sending a rejection message. In a cluster, clustered clients will fail over to another cluster member.
    - Shut down the application if there are stuck threads in the application. The application is shutdown by bringing it into ADMIN mode. All Work Managers belonging to the application are shut down, and behave as described above.
    - Mark the server instance as failed and shut it down it down if there are stuck threads in the server. In a cluster, clustered clients that are connected or attempting to connect will fail over to another cluster member.
    You can configure the "ServerFailureTriggerMBean" in the "OverloadProtectionMBean".
    Below is documentation link for "ServerFailureTriggerMBean" methods.
    http://download.oracle.com/docs/cd/E12839_01/apirefs.1111/e13945/weblogic/management/configuration/ServerFailureTriggerMBean.html
    You can use getStuckThreadCount() method to check the number of stuck threads and transition the server to Failed State once itreaches the limit.
    getStuckThreadCount:
    int getStuckThreadCount() - The number of stuck threads after which the server is transitioned into FAILED state. There are options inOverloadProtectionMBean to suspend and shutdown a FAILED server. By default, the server continues to run in FAILED state. If the StuckThreadCount value is set to zero then the server never transitions into FAILED server irrespective of the number of stuck threads.
    Returns:
    The StuckThreadCount value
    Default Value:
    0
    Maximum Value:
    java.lang.Integer.MAX_VALUE
    Minimum Value:
    0
    Below is documentation link for "OverloadProtectionMBean" methods.
    http://download.oracle.com/docs/cd/E11035_01/wls100/javadocs_mhome/weblogic/management/configuration/OverloadProtectionMBean.html
    In the Admin console, you can set the "FailureAction" under Servers->Configuration->Overload to force shutdown the managed server once the server is in Failed state.
    The OverloadProtectionMBean has a method getFailureAction to achieve the same.
    getFailureAction:
    String getFailureAction() - Enable automatic forceshutdown of the server on failed state. The server self-health monitoring detects fatal failures and mark the server as failed. The server can be restarted using NodeManager or a HA agent.
    Valid Values:
    OverloadProtectionMBean.NO_ACTION, OverloadProtectionMBean.FORCE_SHUTDOWN, OverloadProtectionMBean.ADMIN_STATE
    If you start the managed servers using node manager, you can enable "Auto Kill if Failed" and "Auto Restart" in the Admin console, under Servers-> configuration->Health Monitoring. Node Manager will take care of restarting the managed server if you enable "Auto Restart".
    You can also configure the "Stuck Thread Count" and "Failure Action" to "Force Immediate shutdown of the Server" from Admin console under servers-> configuration-> Overload. This will help you to shutdown the server when the stuck thread count is reached. But there is no way to release the threads once they are stuck from the configuration.
    Suppose if you set the value of the Stuck Thread Count to 20, The server will be transitioned to failed state once the count reaches 20 and if you enable the Failure Action, the server self-health monitoring detects fatal failures and mark the server as failed.
    Depending on how you are starting the servers (custom scripts or Node Manager or startup scripts,...), you can restart the servers.
    For more details on this please refer to below link:
    http://www.oracle.com/technetwork/articles/entarch/workload-management-088692.html
    Hope this helps.
    Thanks,
    Cris

  • HT4847 I have a new iphone and cannot delete the backup from icloud.  It says that it is in use.  I have read some of the other threads and it only seems to be haphazard solutions. Is there a definite way to fix this? I am not able to change icloud accoun

    I have a new iphone and cannot delete the backup from icloud.  It says that it is in use.  I have read some of the other threads and it only seems to be haphazard solutions. Is there a definite way to fix this? I am not able to change icloud accounts.

    Follow the steps in wjosten's post here: https://discussions.apple.com/message/13356770#13356770 (for Windows, substitute Outlook in step 2).

  • Can we unlock an iphone which one locked with an email address and password.I have no idea about the email address and password for the icloud

    can we unlock an iphone which one locked with an icloud email address and password.I have no idea about the email address and password for the icloud.can any one help me about this.

    It sounds like you are talking about an iPhone that has been Activation Locked.  This article explains:
    http://support.apple.com/kb/PH13695
    If so, the iPhone can never be unlocked without the original Apple ID and password.  This is an anti-theft measure.

  • Hello my company Favorites I would like to first thank you for this wonderful program I have a question about the program. How can I Arabization program In your response to the spread accept me thanks and respect

    Hello my company Favorites I would like to first thank you for this wonderful program I have a question about the program. How can I Arabization program In your response to the spread accept me thanks and respect

    Hi ,
    You might want to refer the following link to find your serial number and activate your software .
    Here is the link for the same.
    https://helpx.adobe.com/x-productkb/global/find-serial-number.html
    Let us know how it goes .We'll do the best possible to get your issue fixed.
    Regards
    Sukrit Dhingra

  • Does any one have good idea about the backup and recovery georaster table?

    Does any one have good idea about the backup and recovery georaster table?
    Best Regards,
    Lin
    Edited by: ylin on 2009-10-10 上午2:07

    for backup and recovery, please follow the standard procedure of general database backup and recovery. you need to backup both the georaster table and all related RDT tables.

  • Slight doubt about the downloading shown on Launchpad mac.

    hello folks!
    I have been worried about the downloading process shown in launchpad's first page is happening instead of second page like in lion! is it happening to you people too?

    It is in the first page.
    # 8
    http://support.apple.com/kb/HT5548

  • Heartbleed virus/vulnerability-I have been hearing about the "heartbleed vulnerability" and told to change all my passwords. Does this apply to Macs? I thought they could not get viruses and this was one of the reasons I got one.

    I have been hearing about the "heartbleed vulnerability" and told to change all my passwords. Does this apply to Macs? I thought they could not get viruses and this was one of the reasons I got one.

    See What is Heartbleed?
    (Fair disclosure: The Safe Mac is my site, and contains a Donate button, so I may receive compensation for providing links to The Safe Mac. Donations are not required.)

  • Doubts about the advantages and disadvantages of BEx Analyzer

    Hi people!
    Do you know in specific. What are the advantages and disadvantages of BEx Analyzer?
    and Do you know the limitations and scope of the bex analyzer?
    Talking about the security issue. What kind of resticciones be applied to end-users to control information. Protecting system
    resources and the information that the user uses, not be manipulated.
    I hope you could answer my doubts
    Ramon
    Thanks

    Hi!
    The standard BEx BI 3.x tools, is no longer available with the SAP NetWeaver 7.0 BI tools; however, it is part of the SAP BI add-on installation that, by default, will install the BW 3.x tools along with the newer BI 7.0 tools.
    We want to prevent unauthorized download of data to excel sheets from users who have installed bex analyzer but are not authorized to do that. Certain users only have to access querys from web and shouldn't have to use reports from bex analyzer.
    The only accepted way to access reports for all users is by using web querys published in our intranet. But many users have bex analyzer installed and we don't want that an unauthorized user download data to a excel sheet via bex analyzer.
    I'm testing with one user with this roles, but bex web template and bex analyzer have similiar object authorizations, and i don't know if is possible prevent unauthorized download of data from excel sheets.
    Final users don't access to bex analyzer by rrmx transaction
    Until know i'm testing with this user roles:
    1. ZBW:BEX_WEB:RFC (for web templates)
    S_RFC:
    ACTVT:     16
    RFC_NAME:
    RFC1
    RSBOLAP_BICS
    RSBOLAP_BICS_CONSUMER
    RSBOLAP_BICS_PROVIDER
    RSBOLAP_BICS_PROVIDER_VAR
    RSOBJS_RFC_INTERFACE
    RSRCI_LOCAL_VIEW
    RSWRTEMPLATE
    SDIFRUNTIME
    SYST
    RFC_TYPE:  FUGR
    2. ZBW:BEX:RFC (for Bex Analyzer):
    ACTVT:     16 
    RFC_NAME:
    RSOBJS_RFC_INTERFACE
    RSR_XLS_RFC
    RZX0
    SDIFRUNTIME
    SM02
    SUNI
    SYST
    RFC_TYPE:  FUGR
    please take in count this points:
    1. Prevent unauthorized download of data to excel sheets from users that should have accees only querys from web not bex analyzer (very important this point)=
    2. what are the disadvantages of BEx Analyzer, if only if limited by excel...from other point like performance, workprocess with long runtimes, memory issues, for said something.
    I don't know if i'm going by good way.
    Somebody could help me?
    Ramon

  • I have a question about the calendar on the ipad2. I have multiple calendars in different colors. Some of the events are filled in with color. Others are just listed with a colored dot in front of the event. Any ideas why events ar showing up differently?

    I have an ipad2 and my question is about the calendar. I set up multiple calendars with different colors. Some of the events show up in filled color. Others only show with a colored dot in front of the event. I can't figure out why some show up one way and others show up differently? Any thoughts?

    On mine the ones that show on a coloured background are all-day events, the ones with dots and just timed events.

  • Doubt about the settlement rule of the Production ORder

    The only default distribution rule allowed for a PP order is PP1 or PP2.  We would need to change that to allow settlement to multiple receivers as a default. If that is the case, we may want to look into a user exit to update the settlement rule during production order creation instead so that the G/L account is correct from the beginning.
    Currently when we create the production order, the settlement rule will default the below, I am not sure if a user exit is able to maintain the Source as 200 (Materials)?
    If yes, we can then add the second rule for Source 100 (Labor and Mfg) via the user exit as well.
    In this case, SAP will not prompt us error of settlement with 200%, as they are from difference Sources.
    now anybody can explain me about the User EXit we have to correct this

    any help on this.. please its very urgent
    thanks in advance

  • Have some doubt regarding the  weblog (Lookup's in XI made simpler)

    Hi All,
    I have created the same scenario as mentioned in Siva's weblog (Lookup's in XI made simpler).
    I having some doubts regarding the scenario, it will be great if you help me to resolve the same.
    I am having a file-file scenario where I need to do lookup in database(MS-Access)  through mapping.
    The standard file-file scenario is in place and in addition I have created a receiver jdbc channel . I  have also created the receiver agreement for the same in the cofiguration.
    While creating the receiver agreement you have to specify the interface name which includes the message type…I have specified the normal format which we specify while configuring the jdbc receiver adapter.
    In the message mapping I have created a advance user defined function as mentioned in your weblog which calls my receiver jdbc channel.
    I have also specified the select query to be executed in the mapping program.
    While testing I am getting the following error
    Cannot produce target element /ns0:Role_MT/URole. Check xml instance is valid for source xsd and target-field mapping fulfills requirements of target xsd
    <b>Can you please suggest me what all I need to do in addition to the file-file scenario for this lookup scenario to work.</b>
    Thanks and Regards
    Rahul

    Hi,
    Following is my user defined function
    //write your code here
    String Query = "";
    Channel channel = null;
    DataBaseAccessor accessor = null;
    DataBaseResult resultSet = null;
    Query = "Select URole from  Lookup where UName = '  " + UName[0] + "  ' and UPassword = '  " + Pwd[0] +" '  ";
    try{
    channel = LookupService.getChannel("DB_service","JDBC_channel_receiver");
    accessor = LookupService.getDataBaseAccessor(channel);
    resultSet  = accessor.execute(Query);
    for(Iterator rows = resultSet.getRows();rows.hasNext();){
    Map rowMap = (Map)rows.next();
    result.addValue((String)rowMap.get("URole"));
    catch(Exception ex){
    result.addValue(ex.getMessage());
    finally{
    try{
    if (accessor!= null) accessor.close();
    catch(Exception ex){
    result.addValue(ex.getMessage());
    Thanks and Regards
    Rahul

Maybe you are looking for

  • Maximum text size for textFormat

    Afternoon everyone, I am working on an application in which text is created dynamically. I seem to be experiencing a maximum size of 130 when using textFormat. I cannot seem to find any references to this limit. Is there a way to get around it? So fa

  • Purchase order distrubution using EDI

    Hi, SAP gurus! I am trying to set up Purchase order distrubution using EDI. ORDERS idocs will be sent through middleware message broker. I added ORDERS idoc in LS partner profile outbound data and set up medium type 6 for PO output. Something else is

  • Importing and retaining greek text from word into IndCS3

    Have a word document in Greek. Word file is in Times New Roman and views in word correctly as font is loaded. I wish to import into Indesign CS3 and format accordingly, but, when I do it does not keep greek language it comes in as all pink missing te

  • Why "All Material in SAP has to be flagged as Inventory Item"?

    I am new in the SAP world. Would like to ask a basic question to experts, Is there anything in SAP that "All Material in SAP has to be flagged as Inventory Item? Can any body explain what is the problem with Flagging Direct Purchase Items as non inve

  • How to get the MM datasource

    hai experts, i have a query regarding the creation of datasource and transfering of MM / PP datasource to BW system from r3 system using LO extraction..as every we use tranfer the datsource of SD only.. for example i have a infocube name bid invitati