This site requires JavaScript, please enable it in your browser!
Greenfoot back
SPower
SPower wrote ...

2012/9/15

Is this thread safe?

SPower SPower

2012/9/15

#
Hi all, I know, the greenfoot APIs aren't thread safe. But, I often use another thread to save and load the highscore(s), and I now do it this way:
// this is all in a subclass of World
private volatile ScoreBoard scoreBoard;
private volatile boolean loaded;

protected synchronized void setScoreBoard(ScoreBoard board)
{
    scoreBoard = board;
    loaded = true;
}

public void act()
{
    if (loaded) {
         addObject(scoreBoard, someX, someY);
    }
}

private class LoaderThread implements Runnable
{
    public void run()
    {
         ScoreBoard b = new ScoreBoard(arguments);
         setScoreBoard(b);
    }
}
I didn't put the code in where I create a new thread, but I guess that's doesn't add much to my question. I hope somebody can give me some advice.
mjrb4 mjrb4

2012/9/16

#
Is this thread safe?
Nope. You seem to be trying to get around the threading issues by marking odd things as synchronized / volatile. Marking a method as synchronized just provides a synchronized context locked on the current object, so if no other code is synchronized on that lock (which it doesn't appear to be in your example) it won't make much difference. And I'm not quite sure what you're trying to achieve with volatile fields, but it's almost definitely not doing what you think it is! Regardless of that though, you create a ScoreBoard object which won't be thread-safe (assuming it's an Actor) because Actor itself isn't threadsafe, so that example can never really work in a guaranteed threadsafe manner. And that's ignoring the potential for race hazards, etc. that could well be an issue, but impossible to say without looking at the rest of your code. What are you trying to achieve by using a separate thread in this way?
SPower SPower

2012/9/16

#
mjrb4 wrote...
What are you trying to achieve by using a separate thread in this way?
I want the scenario to still be responsive, like when you've got an animation going on, it doesn't stop while loading the scoreboard. But anyway, thanks for the info.
mjrb4 mjrb4

2012/9/17

#
It's a valid thing to want to do, and yes, if you *must* do that the only way is to use another thread. I've thrown up an example here that works in a thread-safe (ish) way (see the scenario description, but it's as "thread safe" as is possible.) It essentially works by firing off a separate thread to grab / set the UserInfo data, and provides a (poor-man's) callback when it's done (in the form of a volatile boolean field which can then be safely picked back up from the simulation thread.) This happens twice, once to set the score, then a second time in the ScoreBoard class (modified) to grab back the relevant data.
You need to login to post a reply.