1
private void receive() {
            receive = new Thread(new Runnable() {
            public void run() {
                while (running) {
                        byte[] data = new byte[MAX_PACKET_SIZE];
                        DatagramPacket packet = new DatagramPacket(data, data.length);
                    try {
                        socket.receive(packet);
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                    String str = new String(packet.getData());
                    System.out.println(str);
                }
            }
        }, "receive");
        receive.start();
    }

I need to retrieve a source port which would go like this:

packet.getPort()

but i cann't figure out how do i do that exactly. Every time i try, the value sets to zero when it goes out of scope so it only exists inside the run method, or even while loop.

  • Possible duplicate of [Setting outer variable from anonymous inner class](http://stackoverflow.com/questions/5977735/setting-outer-variable-from-anonymous-inner-class) – khachik Mar 04 '17 at 14:24

1 Answers1

0

Anonymous classes can only refer to final variables, but such variables need not be immutable. A good choice here is AtomicInteger:

final AtomicInteger port = new AtomicInteger();

then in your runnable:

port.set(packet.getPort());

then outside:

receive.start();
receive.join();
System.out.println(port.get());

You need the call to join() too, because start() isn't synchronous or deterministic. If the value is needed elsewhere, you could return/pass port, which is threadsafe.

Bohemian
  • 412,405
  • 93
  • 575
  • 722