0

Basically I'm trying to add a runnable class to a tasking threading class of my own which executes these tasks on a different thread, I need to pass the parameters to the runnable object, but I'm having trouble passing strings as the compiler tells:

"Local variable receiver defined in an enclosing scope must be final or effectively final"

String message = networkMessage.getString();
Game.getInstance().addGameTask(new Runnable() {
            @Override
            public void run() {
                Game.getInstance().playerTalk(player.getId(), message);
            }
});

I tried using Lambda with Runnable to do something as simpler as:

Runnable r = () -> Game.getInstance().playerTalk(player.getId(), mode, receiver, channelId, message);

But the compiler will say the same error.

In C# I would come up with something as simple as:

Game.AddGameTask(() => { Game.PlayerTalk(_player.Id, message, mode, receiver, channelId); });

What can I attempt to achieve something as simple as that? It's task is supposed to be for a game server, so I need to add these "tasks" to an external thread for better functioning and performance.

What is wrong?

Raúl Sanpedro
  • 266
  • 4
  • 15

2 Answers2

1

The simplest solution is to make the receiver variable final, which means once its value is set it cannot be set again. E.g.

final Receiver receiver = new Receiver();

Alternatively you could use an AtomicReference to hold the object and allow access in a thread safe manner.

ᴇʟᴇvᴀтᴇ
  • 12,285
  • 4
  • 43
  • 66
0

You should mark message, player as final, like:

final String message = networkMessage.getString();
Game.getInstance().addGameTask(new Runnable() {
            @Override
            public void run() {
                Game.getInstance().playerTalk(player.getId(), message);
            }
});

This way the lambda version will work. This is a(n implementation) decision for the Java Language (not present in C#, that is the reason it works there).

Gábor Bakos
  • 8,982
  • 52
  • 35
  • 52
  • Not sure where `player` comes from... If it is a member variable, it does not have to be `final`, but if it on the stack, it should be. – Gábor Bakos Apr 30 '15 at 18:45
  • Hmm. Not sure why are there people who thinks this is a wrong answer for the question, or this should be deleted. Could you elaborate? (I answered before the question was marked as a duplicate.) – Gábor Bakos Apr 30 '15 at 18:55