Register a SA Forums Account here!
JOINING THE SA FORUMS WILL REMOVE THIS BIG AD, THE ANNOYING UNDERLINED ADS, AND STUPID INTERSTITIAL ADS!!!

You can: log in, read the tech support FAQ, or request your lost password. This dumb message (and those ads) will appear on every screen until you register! Get rid of this crap by registering your own SA Forums Account and joining roughly 150,000 Goons, for the one-time price of $9.95! We charge money because it costs us money per month for bills, and since we don't believe in showing ads to our users, we try to make the money back through forum registrations.
 
  • Post
  • Reply
Sedro
Dec 31, 2008
I'm having a strange problem with multicast sockets. After starting and stopping senders and receivers a few times, the receiver silently fails (no error, but never receives). The receiver shows up when I run netstat -bano. This happens on two Windows 7 machines.
code:
public class Sender {
	static final String group = "239.255.255.250";
	static final int srcPort = 0;
	static final int dstPort = 3702;
	
	public static void main(String[] args) throws Exception {
		String host = InetAddress.getLocalHost().getHostName();
		String msg = "Hello from " + host;
		
		InetSocketAddress addr = new InetSocketAddress(host, srcPort);
		DatagramSocket socket = null;
		try {
			socket = new DatagramSocket(addr);
			InetAddress grp = InetAddress.getByName(group);
			
			DatagramPacket packet = new DatagramPacket(msg.getBytes(), msg.length(), grp, dstPort);
			while (true) {
				socket.send(packet);
				System.out.println("Sent: " + msg);
				Thread.sleep(5000);
			}
		} finally {
			if (socket != null)
				socket.close();
		}
	}
}
code:
public class Receiver {
	static final String group = "239.255.255.250";
	static final int port = 3702;
	
	public static void main(String[] args) throws Exception {
		InetAddress grp = InetAddress.getByName(group);
		MulticastSocket msocket = null;
		try {
			msocket = new MulticastSocket(port);
			msocket.joinGroup(grp);
	        
			byte[] inbuf = new byte[1024];
			DatagramPacket packet = new DatagramPacket(inbuf, inbuf.length);
			while (true) {
				msocket.receive(packet);
				String data = new String(packet.getData(), 0, packet.getLength());
				System.out.println(String.format("Received from %s - %s", packet.getSocketAddress(), data));
			}
		} finally {
			if (msocket != null) {
				msocket.leaveGroup(grp);
				msocket.close();
			}
		}
	}
}

Adbot
ADBOT LOVES YOU

Sedro
Dec 31, 2008
I figured it out (at least I haven't been able to reproduce the problem again). Apparently the receiver was picking a network interface at random. The fix was to modify the receiver from:
code:
msocket = new MulticastSocket(port);
msocket.joinGroup(grp);
to
code:
msocket = new MulticastSocket(port);
InetAddress localHost = InetAddress.getLocalHost();
NetworkInterface networkInterface = NetworkInterface.getByInetAddress(localHost);
InetSocketAddress groupAddress = new InetSocketAddress(group, 0);
msocket.joinGroup(groupAddress, networkInterface);

Sedro
Dec 31, 2008

tractor fanatic posted:

Why does transfer_wrong1 have a race condition?

If you calculate the total balance of the accounts between the withdrawal and deposit, some money will have disappeared into the void.

Sedro
Dec 31, 2008
I mostly use this (and base, super, etc) when I want to filter autocompletion. Naming conventions like _fieldName solve the naming conficts (safer to avoid them entirely).

There are some cases where it makes stylistic sense:
code:
bool equals(Address other)
{
    return this.street == other.street
        && this.zip == other.zip;
}

Sedro
Dec 31, 2008
Do whatever you want with private fields as far as I'm concerned. I would like to hear your reasoning against the typed equals method though.

Sedro
Dec 31, 2008
I would never write a typed equals without overriding object.equals and object.getHashCode. When I see a typed equals I immediately know that the type implements logical equality without looking at comments/source.

Sedro
Dec 31, 2008
It's important to follow Java naming conventions whether you like them or not. Beyond that, follow the convention used by the project. Java convention says not to prefix variables, so you're right - you'll have to use this.

Curious, how do you guys differentiate interfaces vs implementations?
code:
interface Foo;
class FooImpl implements Foo;

Sedro
Dec 31, 2008
Is there a way to make Netbeans or Maven raise errors/warnings for unchecked auto-unboxing? Currently this code doesn't raise a peep:
code:
Boolean b = null;
boolean b2 = b;

Sedro
Dec 31, 2008
I get warnings for null pointers in general, just not the specific unboxing case. This problem arose because I switched code generators and the new one loves boxed types. Now I have a bunch of NullPointerExceptions waiting to happen with no way to find them.

I just switched IDEs after using eclipse for years because Netbeans' Maven + TomCat integration is so much better. I'm sure IntelliJ is great for standard Java development (I couldn't live without ReSharper).

crazyfish posted:

Have you tried a static analysis tool like FindBugs?
Thanks for this, although it doesn't solve my original problem.

Sedro
Dec 31, 2008
You're comparing strings with the == operator which in Java compares object reference. You need to use equals instead:
code:
String str1 = "f";
String str2 = "f";
str1 == str2 // false
str1.equals(str2) // true

Sedro
Dec 31, 2008
That's why I didn't bring up the indentation or redundant if clause ;)

Sedro
Dec 31, 2008
Your problem is that neither of these statements are true:
code:
sex.equals(male)
sex.equals(female)
So your program happily does nothing. What are the values of those variables? Did you instead mean to write this?
code:
sex.equals("m")
sex.equals("f")

Sedro
Dec 31, 2008

Sab669 posted:

I know there's a brief overview of a few IDEs on the first page, but I was hoping to get a little more information on Netbeans VS Eclipse.

I'm still a student, and when I took a Java course we used NetBeans. I'm taking a Design Patterns course this semester which is also in Java and the professor only lets us use Eclipse. So far, I'm not impressed with it at all- the intellisense seems slow as hell, unconventional hotkeys (at least, compared to what I'm used to) and just all around I don't feel comfortable in the environment.

Goons, why you do prefer one over the other?
I prefer Netbeans now (after years of using eclipse) because its Maven support is a million times better. I finally got fed up with using a bunch of crappy eclipse plugins.

HFX posted:

I would also say Eclipse has a git plugin that work.
Depending on your definition of "works".

Sedro
Dec 31, 2008
Try setting some of those values to temporary variables instead of using long conditionals. Then you can step through with a debugger and examine each value. It's also easier to read.

To answer: selected.getDragArrowPoint() probably returns null, and you are dereferencing it.

Also, if mousePosition.distance returns Integer, I think Java will automatically unbox it for the comparison and throw if the value is null. I'm sure someone will correct me though.

Here's hoping for non-nullable reference types.

Sedro
Dec 31, 2008

I am in posted:

Speaking of which, has anyone tried the Checker Framework and its Eclipse plugin?
Tools like this help, but they're a band-aid over the problem. I haven't used this particular one, but I use something similar in .NET which saves me from writing plenty of boilerplate (which shouldn't be necessary in the first place). This seems much more robust though, so I'll definitely check it out for my next Java project.

My biggest concern would be IDE integration. Horrible plugins for otherwise great tools tend to be a deal-breaker for me.

Sedro
Dec 31, 2008

Grawl posted:

- can I get rid of that one final?
No, Java can only close over final variables.

Personally, I try to make all fields/variables/parameters final. I'm curious, does this have any impact on performance?

Sedro
Dec 31, 2008

Jabor posted:

Assuming a sufficiently smart compiler (i.e. you're not developing for a Blackberry), I wouldn't think so.
I wouldn't think so either. I'm pretty sure final classes and methods have performance implications though, which is why I'm wondering. Does final always get translated to byte code, or is it just a compile-time tool? Can I use reflection to set the value of a final field?

Sedro
Dec 31, 2008

1337JiveTurkey posted:

In that particular case I believe that the javac compiler will bake compile-time constants into any class that actually references it, so it's prohibited.
Maybe it could for simple values, but now you have to recompile every class that depends on the constant if you ever change its value.

Sedro
Dec 31, 2008
You would appear to have two race conditions:
A) Reference is dead initially, and gets GC'd between these calls:
code:
dateref = new SoftReference<ZonedDateTime>(...createdatehere...);
// GC
return dateref.get();
B) Reference is alive initially, and gets GC'd between these calls:
code:
dateref.get() == null // false
// GC
return dateref.get();
Fixed:
code:
public ZonedDateTime getCreatedDate() {
    ZonedDateTime date;
    if (dateref != null) {
        date = dateref.get();
        if (date != null) {
            return date;
        }
    }
    date = ...createdatehere...
    dateref = new SoftReference<ZonedDateTime>(date);
    return date;
}
But this is probably a premature optimization and you should not use this at all

Sedro
Dec 31, 2008
Crappy plugins drove me away from eclipse.


In eclipse the build process was:
1. Make change
2. Maven build
3. Refresh all projects
4. Clean all projects
5. Clean maven
6. Clean web app
7. Clean TomCat working directory
8. Some other "clean" options I forgot?
9. Start server
10. Server didn't start? goto 2
11. Server started but I can't see the change at runtime? goto 2

After switching to netbeans:
1. Make change
2. Build and run

They made the assumption that no third-party tool (including their own plugins) will ever modify the workspace. Since that's obviously not true, they added a million "clean" options to compensate.

Sedro
Dec 31, 2008
You should also mark the fields final so the compiler won't let you change them.

Sedro
Dec 31, 2008
There are methods on File to get the path string.

Sedro
Dec 31, 2008
The problem is in your code. Check whether randomYear is ever getting used.

Sedro
Dec 31, 2008
Read up on the difference between checked and unchecked exceptions.

Sedro
Dec 31, 2008
This doesn't actually do anything:
code:
	public void clear(){
		p_02Node<T> current=head.getNextNode();
		while(current!=head){
			p_02Node<T> next=current.getNextNode();
			current=null;
		}
	}
Setting current=null just nulls out the local reference to the node and has no effect on the state. Clear is really easy in Java:
code:
void clear() {
    head = null;
    tail = null;
}
Also you probably want to store the count as a field.

Sedro fucked around with this message at 16:21 on Apr 16, 2012

Sedro
Dec 31, 2008

fletcher posted:

At any rate, can somebody rip apart my method and tell me why it sucks?
I don't see anything terribly wrong with your logic, although I had to look up the behavior of ArrayUtils.subarray when end > length. However your algorithm is fundamentally different than guava's because guava is lazy:

quote:

The inner lists are sublist views of the original list, produced on demand using List.subList(int, int), and are subject to all the usual caveats about modification as explained in that API.

Sedro
Dec 31, 2008
Is there a way to create a file only if it doesn't exist, free of race conditions? I want this behavior:
File exists -> throw exception
File does not exist -> atomically create the file and increment usage count

Sedro
Dec 31, 2008

I am in posted:

I don't know what usage count means in this context, but java.nio.file.Files.createFile(Path path, FileAttribute<?>... attrs) sounds like it would do that.
By usage count I mean opening and obtaining a handle/native resource to the file from the operating system. Locking the file would be fine too.

That API appears to do what I want, but unfortunately I'm on Java 5 and unable to upgrade. (edit: actually it doesn't do what I want. For some reason I thought it returned a stream.)

Edit: I want the standard behavior of the FileOutputStream and RandomAccessFile constructors, except I want an exception if the file already exists. I could use O_EXCL in Unix, FileMode.CreateNew in .NET, etc. I can't find Java support for this anywhere.

Sedro fucked around with this message at 23:20 on Jul 27, 2012

Sedro
Dec 31, 2008

MEAT TREAT posted:

Since you didn't mention it, Bloch says that the best way to do a Singleton is by extending Enum. :shepface:

Java code:
public enum Foo {
   INSTANCE;
}
Because then you can create a singleton factory
Java code:
public static <T extends Enum<T>> T getInstance(Class<T> clazz) {
    return (T)Enum.getValue(clazz, "INSTANCE");
}

Sedro fucked around with this message at 06:08 on Jul 30, 2012

Sedro
Dec 31, 2008

Kruegel posted:

I'm pretty sure the pom files tell maven what the dependencies are and since you probably just provided the jar file (and not the pom) for javasdk it has no clue what its dependencies are.
Did you run mvn install:install-file off the jar or the pom?

Sedro
Dec 31, 2008

fletcher posted:

php:
<?
public class SomeClass {
  private Map<String, SomeObject> myObjects = new HashMap<String, SomeObject>();

  public Collection<SomeObject> getObjects1() {
    return myObjects.values();
  }

  public Collection<SomeObject> getObjects2() {
    return Collections.unmofidiableCollection(myObjects.values());
  }

  public Collection<SomeObject> getObjects3() {
    return new HashMap<String, SomeObject>(myObjects);
  }
}
?>
Which of these methods is the correct way to be doing things? Or if not one of these, is there something better, such as something that uses .clone()?

You don't want to return an object which gives the caller power to mutate myObjects (requirement 1, be friendly to yourself). You also don't return an object which could surprise the caller by changing when they didn't expect it to (requirement 2, be friendly to the consumer).

Method 1 fails requirements 1 and 2.
Method 2 fails requirement 2.
Method 3 doesn't compile.

The easiest solution is to create a copy:
Java code:
public Collection<SomeObject> getObjects() {
    return new ArrayList<SomeObject>(myObjects.values());
}
Guava's immutable collections are also very nice for creating defensive copies of collections and especially when working with constant data.

Sedro
Dec 31, 2008
The answer is covariance. In Java you use a "wildcard" with the syntax "? extends":
Java code:
List<MyObject> myObjects = new ArrayList<MyObject>();
List<? extends MyInterface> sameObjects = myObjects;
"sameObjects is a list of MyInterface or anything deriving from/implementing MyInterface"

That's actually not true for a mutable list but Java will compile it:
Java code:
public class MyObject2 implements MyInterface {
    @Override
    public String someMethod() {
        return "Goodbye world";
    }
}

sameObjects.add(new MyObject2()); // runtime error

Sedro
Dec 31, 2008

emanresu tnuocca posted:

this method will check if objectToProcess is instanceof GameNode and if it is it will call a static method
This is a red flag that you should probably be using virtual method calls.

It sounds GameNode could be implemented as a composite.
Java code:
interface GameObject {
    void action(long timeToProcess);
}

class GameNode implements GameObject {
    private final ArrayList<GameObject> objects = new ArrayList<GameObject>();

    public void add(GameObject obj) {
        objects.add(obj);
    }

    @Override
    public void action(long timeToProcess) {
        for (GameObject obj : objects) {
            obj.action(timeToProcess);
        }
    }
}

Sedro fucked around with this message at 17:51 on Dec 16, 2012

Sedro
Dec 31, 2008
You can use IDE-based code generation, bytecode desugaring, or use Scala (or some other flavor of not Java).

Sedro
Dec 31, 2008

Internet Janitor posted:

The designers of C# recognized how common this pattern was and provided Attributes to add syntactic sugar which makes it look like you have a public field but provides all the functionality of wrapping the field in methods.
I think you mean properties.

Sedro
Dec 31, 2008
You have an off-by one: you will never defect more than once in a row.

Sedro
Dec 31, 2008
You could try ProGuard if your use-case permits.

Sedro
Dec 31, 2008

armorer posted:

Your set up is extremely common for maven, and not really a problem. (Although your parent pom should NOT include dependencies on projects that reference the parent pom itself, that would create a screwy circular dependency and be problematic. It sounds like maybe you have done this? The parent pom should only specify other common dependencies, it should not depend on things that depend on it.)
You can use dependencyManagement in the parent/aggregate pom without introducing circular dependencies:

parent/pom.xml
XML code:
<project ...>
    <modelVersion>4.0.0</modelVersion>

    <groupId>org.example</groupId>
    <artifactId>parent</artifactId>
    <packaging>pom</packaging>
    <version>2.0</version>

    <modules>
        <module>module-common</module>
        <module>module-app1</module>
    </modules>

    <dependencyManagement>
        <dependencies>
            <dependency>
                <artifactId>module-common</artifactId>
                <groupId>${project.groupId}</groupId>
                <version>${project.version}</version>
            </dependency>
            <dependency>
                <artifactId>module-app1</artifactId>
                <groupId>${project.groupId}</groupId>
                <version>${project.version}</version>
            </dependency>
        </dependencies>
    </dependencyManagement>
</project>
module-common/pom.xml
XML code:
<project ...>
    <parent>
        <artifactId>parent</artifactId>
        <groupId>org.example</groupId>
        <version>2.0</version>
    </parent>

    <modelVersion>4.0.0</modelVersion>
    <artifactId>module-common</artifactId>
</project>
module-app1/pom.xml
XML code:
<project ...>
    <parent>
        <artifactId>parent</artifactId>
        <groupId>org.example</groupId>
        <version>2.0</version>
    </parent>

    <modelVersion>4.0.0</modelVersion>
    <artifactId>module-app1</artifactId>

    <dependencies>
        <dependency>
            <artifactId>module-common</artifactId>
            <groupId>${project.groupId}</groupId>
        </dependency>
    </dependencies>
</project>
Now any time you add a fix, you increment the parent pom version, point all modules to the new parent, then build the parent.

Sedro
Dec 31, 2008
Yes, you would use the same version for each module and develop/release them as a single unit. Sometimes I don't need the granularity that Maven provides. For example, my application might reference a separate module containing binary resources (separated for reasons outside of maven), and the two artifacts must be deployed together.

Adbot
ADBOT LOVES YOU

Sedro
Dec 31, 2008
I'm looking for something to administer processes distributed across servers. I want to add, remove, start, stop, and configure the processes from a central location. The processes themselves are implemented in Java (or something else which interfaces through Java), but some other communication mechanism like web services would also be fine. Mainly I want a nice UI (web based or thick client) which does all this administration without much integration work on my part. Any recommendations?

  • 1
  • 2
  • 3
  • 4
  • 5
  • Post
  • Reply