Java synchronization mechanism allows two threads to hold the same lock?

Dear all,
I am a little bit puzzled since I cannot explain why I get the following behavior.
I have a small Java program to draw components. The drawings are cached in the memory for performance improvements. The cache is access by two different threads. Now the funny thing: even I synchronized every access to the cache, I still get ConcurrentModificationExceptions.
Here is a part of the code:
     @Override public void paint(Graphics g2) {
          // Check if the image is in the cache
          Image drawing;
          synchronized (m_Cache) { drawing = m_Cache.get(m_CurrentOffset); }
          if (drawing == null) {
               // The image is not cached, so draw it
               // Put the image into the cache
               synchronized (m_Cache) { m_Cache.put(m_CurrentOffset, drawing); }
     public void componentResized(ComponentEvent e) {
          // Upon resizing of the component, adjust several pre-calculated values
          // And flush the cache
          synchronized (m_Cache) { m_Cache.clear(); }
     public void elementUpdated(IHexGridElement Element) {
          // Clear cache where the element may be contained at
          synchronized (m_Cache) { for (Point p : m_Cache.keySet()) { if (isElementInScope(Element.getIndex(), p, new Point(p.x + m_MaxColumn, p.y + m_MaxRow))) { m_Cache.remove(p); } } }
     }The paint and componentResized methods are invoked by the AWTEventQueue-0 thread. The elementUpdated method is invoked by "MyThread" thread.
Now my question is why do I get java.util.ConcurrentModificationException, especially in situations where a lot of repaintings have to be done and the window is resized? When I remove the caching stuff, everything works perfect, but only a little bit slow.
Thanks for any help.

In your elementUpdated method, you are using an Iterator to walk over the set of keys in your map. You can't see the Iterator, because you are using the new for-each loop syntax which hides it from you - but it's there under the covers. You are then removing elements from your map directly. This is what causes your ConcurrentModificationException.
You should re-write your loop to explicitly use an iterator, and then do your remove operation through the iterator.
Incidentally, you have a slight race condition in your paint method. Two (or more) threads could simultaneously discover that a given image is not cached, then both draw it, then both cache it. If the drawing operation produces the same drawing every time, then the only problem this causes is the overhead of drawing the image multiple times. To fix this, wrap the get, draw and put operations in a single synchronized block.

Similar Messages

  • How can multiple threads hold the same lock?

    I was always under the impression that no 2 threads could hold a lock for the same object, and yet the HotSpot traces say this is happening all the time.
    For example Object 0x0a6c1bf8 is locked in 2 threads:
    "10.129.24.35-1" daemon prio=6 tid=0x2836bad0 nid=0x9d4 runnable [0x2b28f000..0x2b28fc9c]
    at java.net.PlainSocketImpl.socketConnect(Native Method)
    at java.net.PlainSocketImpl.doConnect(PlainSocketImpl.java:333)
    - locked <0x2493f6e0> (a java.net.SocksSocketImpl)
    at java.net.PlainSocketImpl.connectToAddress(PlainSocketImpl.java:195)
    at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:182)
    at java.net.SocksSocketImpl.connect(SocksSocketImpl.java:366)
    at java.net.Socket.connect(Socket.java:519)
    at org.jacorb.orb.factory.PortRangeSocketFactory.doCreateSocket(PortRangeSocketFactory.java:142)
    at org.jacorb.orb.factory.AbstractSocketFactory.createSocket(AbstractSocketFactory.java:54)
    at org.jacorb.orb.iiop.ClientIIOPConnection.createSocket(ClientIIOPConnection.java:313)
    at org.jacorb.orb.iiop.ClientIIOPConnection.connect(ClientIIOPConnection.java:160)
    - locked <0x0a6c1b98> (a org.jacorb.orb.iiop.ClientIIOPConnection)
    at org.jacorb.orb.giop.GIOPConnection.sendMessage(GIOPConnection.java:934)
    - locked <0x0a6c1bf8> (a java.lang.Object)
    at org.jacorb.orb.giop.GIOPConnection.sendRequest(GIOPConnection.java:900)
    at org.jacorb.orb.giop.ClientConnection.sendRequest(ClientConnection.java:323)
    at org.jacorb.orb.giop.ClientConnection.sendRequest(ClientConnection.java:304)
    at org.jacorb.orb.Delegate.invoke_internal(Delegate.java:1024)
    - locked <0x0d434a88> (a java.lang.Object)
    at org.jacorb.orb.Delegate.invoke(Delegate.java:939)
    at org.omg.CORBA.portable.ObjectImpl._invoke(ObjectImpl.java:80)
    at com.company.MyApp._StateChangeListenerStub.newChanges(_StateChangeListenerStub.java:33)
    at com.company.MyAppManager.ListenerOneway.send(ListenerOneway.java:65)
    at com.company.MyAppManager.Sender.run(Sender.java:139)
    "ClientMessageReceptor840" daemon prio=6 tid=0x2a3ab988 nid=0x6b4 in Object.wait() [0x2f70f000..0x2f70fb1c]
    at java.lang.Object.wait(Native Method)
    at java.lang.Object.wait(Object.java:474)
    at org.jacorb.orb.giop.GIOPConnection.waitUntilConnected(GIOPConnection.java:278)
    - locked <0x0a6c1bf8> (a java.lang.Object)
    at org.jacorb.orb.giop.GIOPConnection.getMessage(GIOPConnection.java:318)
    at org.jacorb.orb.giop.GIOPConnection.receiveMessages(GIOPConnection.java:464)
    at org.jacorb.orb.giop.MessageReceptor.doWork(MessageReceptor.java:71)
    at org.jacorb.util.threadpool.ConsumerTie.run(ConsumerTie.java:61)
    at java.lang.Thread.run(Thread.java:595)
    Have I miss-interpreted the HotSpot stack trace?

    To summarise they are both in a synchronized block on the same mutex/Object, but one is in a wait and one isn't.
    So then it follows that if the HotSpot thread reads " - waiting on <address>" like:
    "SomeThread" daemon prio=6 tid=0x29a06658 nid=0xf28 in Object.wait() [0x2b18f000..0x2b18fa1c]
    at java.lang.Object.wait(Native Method)
    - waiting on <address> (a javax.swing.TimerQueue)
    at com.comp.SomeThread.run(TimerQueue.java:236)
    - locked <0x09539510> (a javax.swing.TimerQueue)
    at java.lang.Thread.run(Thread.java:595)
    then it means that the thread is trying to enter the synchronized block on the same mutex/Object but it can't because there is another thread in there which is running, so it is waiting on the outside of the lock instead of the inside of the lock like "ClientMessageReceptor840".
    Ok, I think I get it now. Thanks everyone for your help.

  • Will itunes allow two ipods to share the same library?

    Hello,
    My wife is getting an ipod soon and we want to have our entire library on both ipods. Do I need to do anything special or just will itunes just sync our library to both ipods automatically? I really don't want to screw around with multiple users or playlists.
    Thanks

    No problem. iTunes will recognize each iPod as a separate device. Since you want to have the whole library on each iPod, just plug it in and select your sync options.
    If you ever decide you have different tastes in music, here are some options for managing your iPods: How to use multiple iPods with one computer, http://support.apple.com/kb/HT1495

  • Two objects created at the same time with the same hashcode

    We have this object with the following constructor:
    2010-06-24 00:10:31,260 [LoadBalancerClientSubscriber(3)(pid:24312)] INFO  com.intel.swiss.sws.netstar.application.caching.framework.data
    set.synchronizer.DatasetSynchronizer - Initializing dataset synchronizer for: [/nfs/iil/iec/sws/work/damar/ds_cama/tmp/ds_126631277304794
    /d81], i am com.intel.swiss.sws.netstar.application.caching.framework.dataset.synchronizer.DatasetSynchronizer@2ed3cae0
    2010-06-24 00:10:31,260 [LoadBalancerClientSubscriber(5)(pid:24315)] INFO  com.intel.swiss.sws.netstar.application.caching.framework.data
    set.synchronizer.DatasetSynchronizer - Initializing dataset synchronizer for: [/nfs/iil/iec/sws/work/damar/ds_cama/tmp/ds_126631277304794
    /d31], i am com.intel.swiss.sws.netstar.application.caching.framework.dataset.synchronizer.DatasetSynchronizer@2ed3cae0Note that two objects are created by different threads with exactly the same hash code. Any idea if/how this is possible?

    isocdev_mb wrote:
    The last part definitely suggests already that relying on uniqueness is incorrect. Hash codes are very often equal on distinct objects, viz. new String("java").hashCode == new String("java").hashCode(). Use a class level counter as suggested earlier.For that case we would of course expect the hashCodes to be equal, since the objects are equal. But even in the case of non-equal objects that don't override hashCode, you can still get the same value. Or, for that matter, non-equal objects that do override it. There are 2^32 possible hashCode values. There are 2^64 possible Long values. That means that there are 2^32 Longs that have a hashCode of 1, 2^32 Longs that have a hashCode of 2, etc.
    And for non-equal objects...
    package scratch;
    import java.util.Set;
    import java.util.Map;
    import java.util.HashMap;
    public class HashCodeIsNotUnique {
      public static void main(String[] args) throws Exception {
        Map<Integer, Integer> hashCodeCounts = new HashMap<Integer, Integer>();
        int numObjects = 10000;
        for (int i = 0; i < numObjects; i++) {
          Object obj = new Object();
          int hashCode = obj.hashCode();
          if (!hashCodeCounts.containsKey(hashCode)) {
            hashCodeCounts.put(hashCode, 0);
          hashCodeCounts.put(hashCode, hashCodeCounts.get(hashCode) + 1);
        for (Map.Entry<Integer, Integer> entry : hashCodeCounts.entrySet()) {
          int key = entry.getKey();
          int value = entry.getValue();
          if (value > 1) {
            System.out.println(key + " occurred " + value + " times");
    9578500 occurred 2 times
    14850080 occurred 2 times

  • Multiple Threads writing to the same stream and "Write End Dead"

    Hi, I'm wondering what is the proper method for having multiple threads write to the same stream.
    Right now I have PipedWriter that I give to several Threads.
    However the JLS specifies that when the thread writing to PipedWriter dies, an exception will be generated. Does it mean that I may get a "write end dead" exception when any of the threads dies?
    More specifically I'm trying to extract keywords from a set of pages and print out keywords with their contexts (using threads to avoid a single blocked pages from blocking entire process)

    Your topic says "stream" but your post says "writer" - there's a difference. Readers/writers use the native encoding (which is correct if, for example, you're reading .DOC files created in Windows) while streams use UTF-8 encoding (which is correct if you've got one java app talking to another).
    Multiple threads can output to the same source. You've probably seen really annoying examples as your own System.out.println()s get intermixed with other JVM output in the JVM's window. Synchronization is going to be a serious issue.
    As to the exception, why not just catch it and ignore it?

  • Share iTunes purchases between two user accounts on the same Mac?

    I have a Macbook Pro, for my bride and I, and a Macbook, for our kids. Both Macs are authorized on my iTunes account.
    So, how can I share an iTunes Store purchased song on my account with my wife's? I understand how to turn on sharing and she can see my songs in iTunes on her account, but she cannot synch them to her iPod.
    Now, I'm allowed to authorize an iTunes account on up to five Macs. I have two. But I have four accounts. Either way, I won't be exceeding five copies, but can't find a way to get a song I bought in my iTunes to my wife's iPod.
    We use the same iTunes account but don't want to have to buy things twice to get them on her iPod. Just seems weird that I could put it on five machines but not two user accounts on the same one.
    Message was edited by: Sky Guy

    On my Mac Pro I moved the entire library to "Macintosh HD/Shared/iTunes". Changed the Folder location in iTunes Preferences->Advanced->General to point to that location. Then in each user change the Music/iTunes folder to be an alias or link pointing to the Shared/iTunes folder. You will likely need to change the permissions on that folder to give everyone the ability to read and write. Do that via "Get Info" on the iTunes folder using Finder. I'd suggest backing everything up before you do this.

  • Two different Resultsets for the same query (running at the same time)

    I am using the Thin Driver for Oracle 8.1.6. I am invoking queries in multithreading mode (each thread has his own connection to the oracle DB). If i am invoking the same SQL-Statement in two different threads nearly at the same time, only the ResultSet of the first query is complete. The ResultSet of the second query is not complete (the number of tuples differs each time I run the program). Principally the two ResultSets should be the same (no changes are done at the same time in the DB), but they are not.
    Anybody knows this problem and knows how to solve it? Principally read accesses on DBs should not make such trouble ...
    I hope anybody can help me.

    Pranav,
    As this BADI is having option checked 'Multiple use'. You can implement multiple implementations.
    You need not to deactivate the existing implementation.
    Reddy

  • Exporting two remote objects on the same port

    Hi,
    I would like to export two remote objects on the same host, same port and bind them with different service names.
    There is no problem when I do that from the same Java program.
    But when I export and bind an object from a Java program 1, I cannot do the same with the second (and similar) Java program 2. This is the stack trace of my Exception:
    java.rmi.server.ExportException: Port already in use: 50040; nested exception is:
         java.net.BindException: Address already in use: JVM_Bind
         at sun.rmi.transport.tcp.TCPTransport.listen(TCPTransport.java:243)
         at sun.rmi.transport.tcp.TCPTransport.exportObject(TCPTransport.java:178)
         at sun.rmi.transport.tcp.TCPEndpoint.exportObject(TCPEndpoint.java:382)
         at sun.rmi.transport.LiveRef.exportObject(LiveRef.java:116)
         at sun.rmi.server.UnicastServerRef.exportObject(UnicastServerRef.java:145)
         at sun.rmi.server.UnicastServerRef.exportObject(UnicastServerRef.java:129)
         at java.rmi.server.UnicastRemoteObject.exportObject(UnicastRemoteObject.java:275)
         at java.rmi.server.UnicastRemoteObject.exportObject(UnicastRemoteObject.java:178)
         at java.rmi.server.UnicastRemoteObject.<init>(UnicastRemoteObject.java:75)Can some one help please

    It should work in any version of Java as long as the server socket factories are null or equal according to Object.equals() or its override in the SSF.equals() method if any. Which needs to be present and needs to take the form:
    public boolean equals(Object object)
      return object != null && object.getClass() == this.getClass();
    }with further tests if the server socket factories have additional state.

  • How do I set up two email address on the same account?

    Using Mail in Mac OS X 10.6.2 and moving to Mac for the first time, I have been unable to set up two email addresses on the same account. Entering them, separated by commas, as advised in the Help does not seem to work. I have tried making them both the same password and have tried separating the passwords with a comma but no luck. Unable to set up another account for the second address because it correctly tells me that the account already exists.
    Is there a way?
    Thanks for any help.
    AllanGlen

    After a comprehensive trial and error session, using a new Guest Account each time to be sure of no contamination from the previous trial, I have finally cracked it!
    The problem was logging on to the outgoing server.
    Setting up the first account was fairly straightforward but if I allow Mail to do it automatically I am unable to send because Mail has defaulted to 'Authentication Required' when my server does not require it. Setting the account manually without authentication enables send and receive to work OK.
    If i try to set up the second account automatically, Mail crashes.
    If I set it up manually and choose 'No Authentication', Mail crashes.
    If I set it up manually and choose 'Authentication Required' and enter the full email address as the User Name together with password, Mail crashes.
    If I set it up manually and choose 'Authentication Required' and enter the first part of the email address together with password, Mail crashes.
    However, if I set it up manually and choose 'Authentication Required' and enter the first part of the email address as User Name and no password, Mail accepts it and sets up the account.
    At this point the account receives mail but cannot send it.
    If I go into the Mail preferences and try to edit the outgoing server details, Mail will not accept no Authentication.
    I eventually found that if I uncheck the 'Always Use This Server' box, all account then use the server on the first account, which is correctly set up.
    Now I have my four email accounts all able send and receive.
    One little concern remains. In Outlook Express I could look at the properties of a received email and see what address it had come from, together with many other details. I haven't found out yet whether this can be done in Mail. I just wonder whether if I reply to some email, it will appear to have come from a different address from the one it was sent to.
    Thanks again for all the inputs.
    Allan

  • Two AM's with the same name but different forms causes Deployment problems

    Two Masters forms, DOC & PM are cloned except for the "where clause" in the View's query and the titles in their JSP's.
    DOC workspace has a BC project and a BC4JSP Project. The BC project comprises of the EO and VO named ComVsStaticValue. In the Edit prop-> query for the VO I have specified the "where clause" as VSSV_VS_CODE='DOCTOR'.
    In Java Webserver :-
    The JSP's are located in C:\source\Doctor\ .. and the *.xml and *.class files generated by the BC proj is in C:\source\Doctor\pol_ValueSet\..
    If I execute Doctor in JWS the records are getting filtered properly.
    PM workspace has a BC project and a BC4JSP Project. Again The BC project comprises of the EO and VO named ComVsStaticValue. In the Edit prop-> query for the VO I have specified the "where clause" as VSSV_VS_CODE='PAY_MODE'.
    In Java Webserver :-
    The JSP's are located in C:\source\PMode\ .. and the *.xml and *.class files generated by the BC proj is in C:\source\PMode\pol_ValueSet\..
    If I execute PM in JWS, the PM's JSP comes (the title is correct) but the records pertaining to DOC appears. I checked the View's xml file in C:\source\PMode\pol_ValueSet\ the "where clause" is correct. The xml & classes have the same name but their contents are different.
    I want to know whether this problem is because both have the same name for the AM and the BC4JSP's property file.
    Please clarify.

    Deploying two app modules with the same name will definitely cause problems.
    The JSPs use the information in the properties file to connect to the application module and get the data they need from the appropriate View Objects in those app modules. If you have two app modules with the same name, when a JSP tries to connect, it has no way of knowing which one of the app modules to connect to if they both have the same name.
    You could:
    1. Just use one application module that contains all the View Objects you need to access.
    or
    2. Rename one of the application modules or the package it is located in so the names are distinct. If you choose this method, you will also need to update the JSPs (specifically the 'registerApplicationFrompPopertyFile' method call), and your JSP project's appmodule property file.

  • Can you put two iTunes libraries on the same computer? what is the best way?

    Is it possible to put two iTunes libraries on the same computer?  What is the best way to do it so the two libraries are not connected?

    MSGTN wrote:
    Is it possible to put two iTunes libraries on the same computer?
    yes.
    What is the best way to do it so the two libraries are not connected?
    give them distinct names. launch iTunes while holding the option (⌥) key, click on choose library when prompted, and select the iTunes folder of the desired library.
    FWIW, there are 3rd party apps that help with managing multiple libraries, notably:
    PowerTunes
    iTunes Library Manager

  • I need to have two time zones on the same iCal appointment

    I work accross four time zones, two of which do not observe Daylight Saving Time (DST). This means that when I'm booking my flights on iCal, it would be usefull to have two time zones in the same iCal appointment (Outlook, for instance, allows this). What I currently do is to choose one of the time zones as the iCal appointment and then I "translate" the other time to the one I'm using on iCal.
    This is quite a challenge, though:
    if I'm taking a flight from Luanda (WAT = GMT+1, no DST) to London (GMT with DST) I would like to book it on iCal exactly like it shows on the ticket , 21:00 (WAT) to 06:00 (GMT).
    Using the "translated approach", from May to October, this means 21:00 (GMT) to 06:00 (GMT).
    Using the same approach, from November to April it means from 20:00 (GMT) to 06:00 (GMT).
    If I include Jo'burg (CAT = GMT+2, no DST) and Frankfurt (GMT+1 with DST), booking flights in your calendar becomes quite a challenge!
    Does anyone know if this feature is planned for any future versions of iCal?

    Hi,
    This is not possible in iCal. The nearest thing would be to create two events, one for take off and one for landing.
    Also, this is a user to user forum. By posting here you are not guaranteed someone from Apple will read it. If you'd like Apple to know about your suggestion I reccommend you send them feedback.
    Best wishes
    John M

  • Mac on Windows SMB Share- IDLK files disappearing allowing several users to access the same file

    Hi,
    We have a volume licensing agreement with Adobe and have around 16 Adobe CS6 licenses all used on Macs. The network is based around Windows servers and shares which the Macs connect to via an SMB connection to the server. The issue we're having is that when an InDesign file is opened, sometimes it will not create an IDLK file (or sometimes it will create one but it will disappear seconds later) and it allows several people to view the same file at the same time. Obviously two or more people working on the same file can, will and has caused issues with overwriting documents without knowledge of doing so.
    Has anyone else encountered this or have any ideas as to what might help us resolve this issue?
    Thanks

    When you open a file from a previous version (you'll see converted in
    the file name) there is no CS6 file in existence, yet. Once the file is
    saved as a CS6 file, the lock file is created. The whole procedure is
    designed so that you must make a fully conscious decision to overwrite
    the old version file with a new one.
    This is no different than creating a new document that hasn't been saved
    yet.

  • Can you install CC on two separate computers under the same A/C

    Can you install CC on two separate computers under the same A/C

    yes, adobe single user licenses allow up to two concurrent installation/activations.

  • Play two video files at the same time.

    I am trying to play two video files at the same time. I create two threads, each of which has its own frame, playing button, and builds its own graph to play the file. Now everything seems works except that when the first file is being played and I hit PLAY
    to play the second file, the program plays the second file but the first one is paused; furthermore the control button has no response for the first one. Did I miss anything? Can anyone help me figure out the problem?
    Best,
    Fayin

    You don't need separate threads for 2+ playback pipelines because the filters create worker threads internally and don't block execution on calling thread.
    If you decide to keep separate threads, you will have to follow Michel's advice and have message pumps on those threads.
    You can also have both files in the same graph, in which case you have perfect sync between them (both start playing together in sync), however you cannot pause/stop/run files separately.
    The problem you described is most likely not a DirectShow problem and is rather about generic threading, COM or window messaging.
    http://alax.info/blog/tag/directshow

Maybe you are looking for

  • How to read file with JNI?

    Hello, I want to implement a native function that has as a parameter a File type. For example: public native void readFile(File f); But as far as I know the JNI does not support File type, or I am wrong? One way to solv this problem i of course to co

  • Turning off validation in EVS

    Does the Extended Value Search Service support a mode where there is no validation of the input field value (i.e. the message is not shown in the messageManager)?

  • Recent poor print quality on C5580

    I have had my C5580 for a year or so with no problems. Three days ago the print quality decreased dramatically with all the photos looking very grainy and pixely. I have replaced the ink cartridged, check the print quality which defaults to "best", a

  • Generate complement​ary digital signals with dead time between each pulse and controlled by duty ratio

    I am to generate  two complementary digital signals using NI 9606 conected by RIO Mezannine Card to NI 9683 (Half Bridge DO). I am able to generate the signals but I am not able to put dead time between high and low signal and also, low and high sign

  • Cannot be converted in type DEC,CURR - longtext

    Dear, When we are loading the data to the targets, we are getting the errors in the Transfer rules like mentioned bellow Info source 0EC_CS_1 (Transaction Data for Consolidation) Status (tab) : Technical : Collection in source system ended Processing