简体   繁体   中英

Issue with java boolean

I'm attempting to create a chat client, I'm returning a message from the javaSpace, Then setting newMessage = true; So the client can see that there is a new message that needs to be read.

public void notify(RemoteEvent ev) 
{
    try 
    {
        messageRead = false;
        QueueItem qiTemplate = new QueueItem();
        newMessage = (QueueItem)space.take(qiTemplate,null,Long.MAX_VALUE);
        System.out.println(newMessage.getSender().getName()+ ": " + newMessage.getContent());
    } 
    catch (Exception e) 
    {
        e.printStackTrace();
    }
}

Then for the client,

while(true)
{
    try 
    {
        boolean temp  = _manager.messageRead;
        //System.out.println(temp);
        if(!temp)
        {
            QueueItem nextJob = _manager.newMessage;
            String nextJobNumber = nextJob.getSender().getName();
            String nextJobName = nextJob.getContent();
            System.out.println(nextJob.getSender().getName()+ ": " + nextJob.getContent());
            jobList.append( nextJobNumber + " : " + nextJobName + "\n" );

            _manager.messageRead = true;
        }



    }  catch ( Exception e) 
    {
        e.printStackTrace();
    }
}

That right now will ALWAYS return _messager.messageRead to be true, even though I've just set it too false. If I uncomment //System.out.println(temp); the boolean will then for some reason be updated and it will equal what its meant too.

I've never come across this error before and its extremely strange to me, So I'm hoping someone can help.

You don't seem to have synchronized accesses to your boolean flag messageRead . println happens to do that for you hence what you observe.

You could probably fix your issue by decalring the flag volatile:

private volatile boolean messageRead;

That will ensure that changes you make in one thread are visible from another thread without needing to synchronize your code.

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