简体   繁体   中英

Does making variable volatile get rid of: Multithreaded correctness - Inconsistent synchronization

I'm getting Inconsistent synchronization error on sonar on following code.

public int getMessageCount()
{
return m_messageCount;
}

public void onMessage(XQMessage msg) throws XQServiceException
{
  synchronized(this)
  {
    m_messageCount--;
    // add the message to the result
    m_messages.add(msg);
    if (m_messageCount == 0)
    {
      // wake up client
      finished();
    }
  }
}

Error is on "return m_messageCount". If i make m_message volatile, will it solve the issue?

Since you are using synchronized(this) when you modify m_messageCount you can make the getMessageCount() method synchronized and that will solve your problem.

For example:

public synchronized int getMessageCount(){
    return m_messageCount;
}

@jameslarge Can you give this AtomicInteger suggestion in separate post

I was thinking, something like this:

static final int INITIAL_MESSAGE_COUNT = ...;

AtomicInteger messageCount = new AtomicInteger(INITIAL_MESSAGE_COUNT);

public int getMessageCount()
{
    return messageCount.get();
}

public void onMessage(XQMessage msg) throws XQServiceException
{
    int mc = messageCount.decrementAndGet();
    messages.add(msg);
    if (mc == 0) wake_up_client();
}

NOTE: the messages.add() call is inside a synchronized block in your implementation. That is no longer the case in my version. I don't know what messages is exactly, but if you were relying on the synchronized block to protect it, you will have to add synchronization back in. At that point you might as well just go with your original version: AtomicInteger is more complicated than just using a regular int . I don't use it except when it allows me to implement some algorithm without using synchronized blocks.


PS; What is supposed to happen if the message count is already zero when onMessage() is called? Can that happen? If it happens, you'll get a negative message count. I don't have enough information to know whether that would be a good thing or a bad thing.


PPS; What about that XQServiceException ? Both of our implementations will decrement the message count regardless of whether or not messages.add() throws an exception. That might not be what you want. I don't know.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM