So, I'm trying to initialize a DatagramSocket in the constructor, and I want this field to be final , but my compiler (i.e. Eclipse) gives me the following error:
An empty field datagram field may not have been initialized
It's clear. Here's the code snippet:
public class Foo { private final int DEFAULT_UDPLISTENPORT = 49400; private final DatagramSocket datagramSocket; public Foo() { synchronized(this) { try { datagramSocket = new DatagramSocket(DEFAULT_UDPLISTENPORT); } catch (SocketException e) {
Now I know that there is a way around this, but this requires creating a temporary variable. Here's the code snippet:
public class Foo { private final int DEFAULT_UDPLISTENPORT = 49400; private final DatagramSocket datagramSocket; public Foo() { synchronized(this) { DatagramSocket tempSocket = null; try { tempSocket = new DatagramSocket(DEFAULT_UDPLISTENPORT); } catch (SocketException e) {
So, I suppose, my question is: is there a more elegant way to do this, or is it something I just need to live with if I want this field to be final ?
EDIT:
For those of you who are interested, here is a solution that I came up with from your recommendations:
public class Foo { private static final Foo INSTANCE; static { try { INSTANCE = new Foo(); } catch (SocketException e) { throw new ExceptionInInitializerError(e); } } private final int DEFAULT_UDPLISTENPORT = 49400; private final DatagramSocket datagramSocket; public Foo() throws SocketException { synchronized (this) { datagramSocket = new DatagramSocket(DEFAULT_UDPLISTENPORT); } } public static Foo getInstance() { return INSTANCE; } }
Please let me know if this is correct, or if you have other suggestions. I appreciate the help!
mre
source share