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
Gravity Pike
Feb 8, 2009

I find this discussion incredibly bland and disinteresting.
I've got a question about creating new objects within generics. What I'm trying to do can be boiled down to this:
code:
public class Environment<U extends Agent, V extends Agent> {
   U agt1;
   V agt2;
   public void reset() {
      agt1 = new U();
      agt2 = new V();
   }
}
This doesn't work. I've been looking at The Java Tutorials, but I'm having trouble with something in this one, or am looking at the wrong thing entirely. I have tried this:
code:
public class Environment<U extends Agent, V extends Agent> {
   U agt1;
   V agt2;
   public void reset() {
      agt1 = agt1.getClass().newInstance();
      agt2 = agt2.getClass().newInstance();
   }
}
but it didn't work. Can anyone point out what I'm doing wrong?

Adbot
ADBOT LOVES YOU

rjmccall
Sep 7, 2007

no worries friend
Fun Shoe
After type-checking is done, Java lowers generic types to non-generic types using an technique called "type erasure", which is pretty much exactly what it sounds like: a type parameter T extends B is erased to the (erasure of) B. So at runtime, that code has no idea what T was.

The main technique for fixing this (if you really need to create new objects within generic code) is to pass in some object which is capable of creating an object of the appropriate type. Something like this:

code:
interface Make<T> {
    T make();
}

public class Environment<U extends Agent, V extends Agent> {
   public Environment(Maker<U> umaker, Maker<V> vmaker) {
     umaker_ = umaker;
     vmaker_ = vmaker;
   }

   Maker<U> umaker_;
   Maker<V> vmaker_;
   U agt1;
   V agt2;
   public void reset() {
      agt1 = umaker_.make();
      agt2 = vmaker_.make();
   }
}
If you want to go for convenience rather than generality, you can use Class<U> instead of defining your own interface, in which case the method to call is newInstance(). But reflection is bad mojo.

dealmaster
Dec 24, 2005

Somebody call for an exterminator?
Does anyone know how to rename a File object? What I'm trying to do is get the proper extension appended to the end of a provided filename. I've tried using the renameTo() function, but in my experience and from what I can see online, it has numerous issues especially on Windows platforms. I'm using a JFileChooser for my file dialog, here's a snippet of my code:

code:

                JFileChooser fc = new JFileChooser("C:\\Program Files\\Test");

		JCheckBox cb = new JCheckBox("Automatically append extension");
		fc.setAccessory(cb);

		int returnVal = fc.showSaveDialog(new JFrame());

    		if(returnVal == JFileChooser.APPROVE_OPTION) {
		    File file = fc.getSelectedFile();

		    System.out.println(fc.getName(file));

		    if(cb.isSelected()) {
			//Append ".pd" to filename
			File newFile = new File(file.getAbsolutePath() + ".pd");
			System.out.println(newFile.getAbsolutePath());
			boolean worked = file.renameTo(newFile);

			if(worked)
			    System.out.println("yay");
			else
			    System.out.println("nuts");
		    }
Oddly enough, "nuts" gets printed out if I enter a filename like "testfile" in the file dialog and click save, as long as a file named "testfile" doesn't exist in the directory that I'm trying to save in. However, if a file named "testfile" already exists and I try to save a file called "testfile", the rename works and "testfile.pd" is created and "yay" is printed. For the life of me, I can't figure this out, why is this happening?

rjmccall
Sep 7, 2007

no worries friend
Fun Shoe
File is misnamed. A File object just represents an abstract filesystem path. JFileChooser is giving you the abstract filesystem path that the user chose to save the file to. file.renameTo(newFile) is literally trying to rename an existing file at the abstract path given by file to the new path given by newFile, which is why it fails when no such file exists.

Files are immutable, just like Strings. If you don't like the path the user gave you, make a new File object and use it instead. In other words, do this:

code:
if(cb.isSelected()) {
  //Append ".pd" to filename
  file = new File(file.getPath() + ".pd");
}

dealmaster
Dec 24, 2005

Somebody call for an exterminator?

rjmccall posted:

File is misnamed. A File object just represents an abstract filesystem path. JFileChooser is giving you the abstract filesystem path that the user chose to save the file to. file.renameTo(newFile) is literally trying to rename an existing file at the abstract path given by file to the new path given by newFile, which is why it fails when no such file exists.

Files are immutable, just like Strings. If you don't like the path the user gave you, make a new File object and use it instead. In other words, do this:

code:
if(cb.isSelected()) {
  //Append ".pd" to filename
  file = new File(file.getPath() + ".pd");
}

Thanks very much, I appreciate this and I can't believe I overlooked such a simple solution. I had it in my head that I had to use renameTo(). I also didn't know that File is immutable, that's valuable information.

useless player
Mar 16, 2009

TRex EaterofCars posted:

What's the fully qualified package for that class? I googled $$$setupUI$$$ and found a groovy project for the intellij ide here: http://www.jetbrains.net/jira/browse/GRVY-2045

Anything look familiar?

Thanks for this. So it turns the project was in fact done using Intellij and that setupUI method was auto-generated by the IDE. I installed Intellij, put the files I had in a project and it looks like everything is working. I don't really get it, but I'm not complaining :).

Volguus
Mar 3, 2009

useless player posted:

Thanks for this. So it turns the project was in fact done using Intellij and that setupUI method was auto-generated by the IDE. I installed Intellij, put the files I had in a project and it looks like everything is working. I don't really get it, but I'm not complaining :).

Are you saying that Intellij is automatically generating a method (that is being called somewhere), and moving to a different IDE (or simple text editor) makes the code to not work anymore?

Well...that's -5 points for intellij off the bat right there. That's moronic.
The other -5 points of course come from the IntelliJ fans :colbert: .


One should be able to compile a java project (any project) using simple command line javac anytime he/she wishes.

Mustach
Mar 2, 2003

In this long line, there's been some real strange genes. You've got 'em all, with some extras thrown in.

rhag posted:

you need to get away from that GUI editor. It's so easy to write a nice UI in java, that using a GUI editor will only slow you down.
Read this: http://java.sun.com/docs/books/tutorial/uiswing/layout/gridbag.html

It tells you how to use it, what all the arguments mean, etc.
This is terrible advice. Writing UIs in procedural code is the slowest, most tedious, most cumbersome, and most error-prone (a.k.a. gayest) way to do it. If there's not a markup language for it (and a lot of the time, even if there is one), a visual editor is the fastest way of coding an interface.

quote:

One should be able to compile a java project (any project) using simple command line javac anytime he/she wishes.
Yes, let's teach beginners to stubbornly ignore all non-Sun libraries and tools like parser generators, etc.

dealmaster
Dec 24, 2005

Somebody call for an exterminator?

Mustach posted:

This is terrible advice. Writing UIs in procedural code is the slowest, most tedious, most cumbersome, and most error-prone (a.k.a. gayest) way to do it. If there's not a markup language for it (and a lot of the time, even if there is one), a visual editor is the fastest way of coding an interface.

Not in my brief experience. The GUI that I built using the visual editor was flimsy and had very strange bugs in it (buttons told to anchor to the bottom-left corner of the page would move away from it of their own accord). I coded it by hand and it is working flawlessly.

Janitor Prime
Jan 22, 2004

PC LOAD LETTER

What da fuck does that mean

Fun Shoe

Mustach posted:

Yes, let's teach beginners to stubbornly ignore all non-Sun libraries and tools like parser generators, etc.

There are these things called JARS that you can include in your project. If your IDE is using some proprietary JARS that aren't being copied in the project folder, it sucks!

Tulenian
Sep 15, 2007

Getting my 'burg on.

Mustach posted:

Yes, let's teach beginners to stubbornly ignore all non-Sun libraries and tools like parser generators, etc.

Instead, let's teach beginners to only compile things that have an <insert magic here> compile step and don't use a standard process. Nothing like some magic to teach them how to write quality software.

Mustach
Mar 2, 2003

In this long line, there's been some real strange genes. You've got 'em all, with some extras thrown in.

MEAT TREAT posted:

There are these things called JARS that you can include in your project. If your IDE is using some proprietary JARS that aren't being copied in the project folder, it sucks!
-cp, among many other things :effort:

Tulenian posted:

Instead, let's teach beginners to only compile things that have an <insert magic here> compile step and don't use a standard process. Nothing like some magic to teach them how to write quality software.
Yep, I was totally arguing in favor of whatever you're talking about instead of arguing against "javac *.java is all you should ever need to do for any project!" I'll restate it without sarcasm: Beginners should be taught that it's okay to use tools like code generators and libraries that don't come with the JDK. Both of these things require understanding their project's build process! Amazing!

Volguus
Mar 3, 2009

Mustach posted:

-cp, among many other things :effort:

Yep, I was totally arguing in favor of whatever you're talking about instead of arguing against "javac *.java is all you should ever need to do for any project!" I'll restate it without sarcasm: Beginners should be taught that it's okay to use tools like code generators and libraries that don't come with the JDK. Both of these things require understanding their project's build process! Amazing!

Well..if you read the guys post, it seems like the IDE was autogenerating a function ($$$setup$$$), probably at compile time.

This is hosed up, no matter how you look at it.
Wanna use a GUI builder? Go ahead. Have fun. But that GUI builder better generate code, not fancy shmancy stuff that will break the second you move away from that IDE/GUI builder.

Yes, you have to be able to use javac to compile a project. Would that be masochistic? Yes. But should you be able to do it, if you want to? You betcha.

Only Shallow
Nov 12, 2005

show
How can I load my read-only Derby database distributed along with my program JAR? For a sound or image I'd use Class.getResource(), but nothing I've found implies that would work here.

I've set Derby's temporary directory and log file to the system temp directory and chmoded the database folder read-only to make sure it works that way. It works perfectly when run from within Eclipse, but when I export my runnable JAR I get the "database not found" SQLException.

My JAR is laid out like this:
code:
.
|-- META-INF
|   `-- services
|-- Database
|   `-- seg0
|-- about_files
|-- javazoom
|   `-- jl
`-- org
    |-- apache
    |-- cooltrainer
    `-- eclipse

Mustach
Mar 2, 2003

In this long line, there's been some real strange genes. You've got 'em all, with some extras thrown in.

rhag posted:

Well..if you read the guys post, it seems like the IDE was autogenerating a function ($$$setup$$$), probably at compile time.

This is hosed up, no matter how you look at it.
Wanna use a GUI builder? Go ahead. Have fun. But that GUI builder better generate code, not fancy shmancy stuff that will break the second you move away from that IDE/GUI builder.
Oops, there were two posters with questions about different GUI builders. Sorry for accidentally jumping to the defense of IntelliJ, which I know nothing about. I do know that NetBeans generates "real" code (and some XML that's used by the designer exclusively to save/load the layout; not for compilation).

Lysidas
Jul 26, 2002

John Diefenbaker is a madman who thinks he's John Diefenbaker.
Pillbug
IntelliJ can generate "real" (Java) code too, but it defaults to creating .class files. It's a configuration option, but I don't remember if it's global or project-specific.

Why, I don't know.

useless player
Mar 16, 2009

rhag posted:

Well..if you read the guys post, it seems like the IDE was autogenerating a function ($$$setup$$$), probably at compile time.
Yeah, that's what happened. The .class file had some extra bytecode that didn't come from the source code. I found the project on elance and bid on it thinking that it would be something simple I could finish in an afternoon. Instead, it took me a few hours (and the help of this thread) just to figure out how to compile and build the damned thing. Lesson learned.

useless player fucked around with this message at 08:23 on Jul 21, 2009

Fehler
Dec 14, 2004

.
I would like to make a Java program extensible by allowing people to write their own classes (derived from a pre-defined class) which I would then load in my program. That way, I'm hoping to make it possible to add certain features without having to recompile the entire program, or even having access to the code.

So basically I'm looking for something like a DLL equivalent in Java. I think I read about something like this once, but I'm unsure on the details. Is there even such a thing in Java? How hard would it be to implement? What are some good starting points?

1337JiveTurkey
Feb 17, 2005

Fehler posted:

I would like to make a Java program extensible by allowing people to write their own classes (derived from a pre-defined class) which I would then load in my program. That way, I'm hoping to make it possible to add certain features without having to recompile the entire program, or even having access to the code.

So basically I'm looking for something like a DLL equivalent in Java. I think I read about something like this once, but I'm unsure on the details. Is there even such a thing in Java? How hard would it be to implement? What are some good starting points?

Every class file is effectively a dll. A classloader like a URLClassLoader is used to load the class from a Jar file, then the class can be instantiated through reflection and used normally.

Volguus
Mar 3, 2009

Fehler posted:

I would like to make a Java program extensible by allowing people to write their own classes (derived from a pre-defined class) which I would then load in my program. That way, I'm hoping to make it possible to add certain features without having to recompile the entire program, or even having access to the code.

So basically I'm looking for something like a DLL equivalent in Java. I think I read about something like this once, but I'm unsure on the details. Is there even such a thing in Java? How hard would it be to implement? What are some good starting points?

I've done something like this once for a program of mine.
Here is my approach to it (it can be done in a gazillion other ways, and half of them could be better than this):

- specify a directory where the plugin jars have to be located (for me it was plugins/)
- specify an information file that has to be in the .jar
in my case , i was looking for an xml file,named plugin.xml, that contained information about what kind of modifications that plugin wanted to make and what classes to load. Something like: Add menu item with text "X", on user click invoke action package1.package2.YourActionClass .
Of course, you can define whatever you want.

- Load up the class using a class loader. In my case I wrote my own, extending the JarClassLoader. The only reason I did that was that I looked in a specific directory for the .jar's, .jar's that normally would not be in the classpath

- Create an instance of the class, and invoke method Y



Hope this helps.

Fehler
Dec 14, 2004

.
Thanks for the suggestions with the XML, but since it will always just be one single class that needs to be loaded, I think I should be fine with a simpler approach.

My concept so far is that the user puts a file extensionName.jar in a special folder and in my program for every .jar in the folder, I try to load a class called "org.me.extension." + extensionName.

Here is my code for that (file is a File object):
code:
try {
	URL jarURL = new File("jar:file://" + file.getAbsolutePath() + "!/").toURI().toURL();
	String className = "org.me.extensions."+file.getName().replace(".jar", "");
	log.info("Loading "+className+" from "+jarURL.toString());

	ClassLoader urlCl = URLClassLoader.newInstance(new URL[] {jarURL});
	Class theClass = urlCl.loadClass(className);
} catch (ClassNotFoundException ex) {
	log.log(Level.SEVERE, null, ex);
} catch (MalformedURLException ex) {
	log.log(Level.SEVERE, null, ex);
}
Unfortunately, I get an exception right now for this:

java.lang.ClassNotFoundException: org.me.extensions.TestClass
at java.net.URLClassLoader$1.run(URLClassLoader.java:200)

Any ideas why? I don't even know how I would go about debugging this...

Max Facetime
Apr 18, 2009

My first guess would be that the TestClass.class file is in the root of the TestClass.jar and not in org/me/extension.

If that's not the case, I'd start debugging by using a JarInputStream to make sure the .jar is good. Maybe compare to a known good .jar.

CoasterMaster
Aug 13, 2003

The Emperor of the Rides


Nap Ghost
I've got a bunch of tasks that need to get done (download some files and do some processing on them) and I'd like these to happen concurrently so I've been using a ThreadPoolExecutor and just shoving Runnables at it. Is there any sane way to have some tasks go to the front of the queue instead of the back (i.e. cutting in line?). There are two ways I've thought to do it:

1) have two ThreadPoolExecutors, one a normal one and one a 'priority' one and put all of the cutting tasks in the priority one

2) have a separate thread that keeps two queues, a normal and priority and continually monitors the ThreadPoolExecutor and gives it the correct job when it's needed.

Is there a better approach here?

baquerd
Jul 2, 2007

by FactsAreUseless

CoasterMaster posted:

I've got a bunch of tasks that need to get done (download some files and do some processing on them) and I'd like these to happen concurrently so I've been using a ThreadPoolExecutor and just shoving Runnables at it. Is there any sane way to have some tasks go to the front of the queue instead of the back (i.e. cutting in line?). There are two ways I've thought to do it:

1) have two ThreadPoolExecutors, one a normal one and one a 'priority' one and put all of the cutting tasks in the priority one

2) have a separate thread that keeps two queues, a normal and priority and continually monitors the ThreadPoolExecutor and gives it the correct job when it's needed.

Is there a better approach here?

FileRetriever implements Runnable, Comparable
PriorityBlockingQueue<FileRetriever>

fletcher
Jun 27, 2003

ken park is my favorite movie

Cybernetic Crumb
Is there a good way to figure out what is wrong with the html I am trying to render as a PDF with Flying Saucer and ITextRenderer? I have to deal with these issues every now and then and it's always a pain trying to figure out what it's throwing up on when I get a stack trace like:

code:
com.caucho.xml.XmlParseException: anonymous.xml:1: expected name at ` '
        at com.caucho.xml.XmlParser.error(XmlParser.java:2972)
        at com.caucho.xml.XmlParser.parseEntityReference(XmlParser.java:1069)
        at com.caucho.xml.XmlParser.parseNode(XmlParser.java:349)
        at com.caucho.xml.XmlParser.parseInt(XmlParser.java:256)
        at com.caucho.xml.AbstractParser.parseImpl(AbstractParser.java:736)
        at com.caucho.xml.AbstractParser.parseDocument(AbstractParser.java:909)
        at com.caucho.xml.AbstractParser.parseDocument(AbstractParser.java:890)
        at com.caucho.xml.AbstractParser.parseDocument(AbstractParser.java:873)
        at com.caucho.xml2.parsers.AbstractDocumentBuilder.parse(AbstractDocumentBuilder.java:81)
Before I've just dumped the html to a text file, and then just comb through that by hand to try to figure out whats wrong. I'm having trouble doing that with this one though...any suggestions?

Mill Town
Apr 17, 2006

fletcher posted:

Is there a good way to figure out what is wrong with the html I am trying to render as a PDF with Flying Saucer and ITextRenderer? I have to deal with these issues every now and then and it's always a pain trying to figure out what it's throwing up on when I get a stack trace like:

code:
com.caucho.xml.XmlParseException: anonymous.xml:1: expected name at ` '
        at com.caucho.xml.XmlParser.error(XmlParser.java:2972)
        at com.caucho.xml.XmlParser.parseEntityReference(XmlParser.java:1069)
        at com.caucho.xml.XmlParser.parseNode(XmlParser.java:349)
        at com.caucho.xml.XmlParser.parseInt(XmlParser.java:256)
        at com.caucho.xml.AbstractParser.parseImpl(AbstractParser.java:736)
        at com.caucho.xml.AbstractParser.parseDocument(AbstractParser.java:909)
        at com.caucho.xml.AbstractParser.parseDocument(AbstractParser.java:890)
        at com.caucho.xml.AbstractParser.parseDocument(AbstractParser.java:873)
        at com.caucho.xml2.parsers.AbstractDocumentBuilder.parse(AbstractDocumentBuilder.java:81)
Before I've just dumped the html to a text file, and then just comb through that by hand to try to figure out whats wrong. I'm having trouble doing that with this one though...any suggestions?

Run it through an online validator like the one at http://validator.w3.org/ ?
Alternatively, if it's a local file and you don't want to upload it, install the Firefox HTML validator plugin http://users.skynet.be/mgueury/mozilla/

Pump-Action Gerbil
Sep 13, 2000
Dumb question about decimal approximations with double variables used to be here.

Thanks quadreb!

Pump-Action Gerbil fucked around with this message at 10:37 on Aug 1, 2009

baquerd
Jul 2, 2007

by FactsAreUseless

Pump-Action Gerbil posted:

Hello, I am just getting started in Java.

Simply, it comes down to the inability of binary to accurately represent the numbers.

Pump-Action Gerbil
Sep 13, 2000

quadreb posted:

Simply, it comes down to the inability of binary to accurately represent the numbers.

Thank you very much. I managed to find a couple articles about this, I will check them out now.

Janitor Prime
Jan 22, 2004

PC LOAD LETTER

What da fuck does that mean

Fun Shoe
I don't know what you original question was but I'm pretty sure it could be fixed by a fixed place decimal class. Java also has the BigDecimal class which is part of the standard library and could probably serve your needs. Just keep in mind that working with theses classes is slower than their primitive counterparts (float, double).

dealmaster
Dec 24, 2005

Somebody call for an exterminator?

MEAT TREAT posted:

I don't know what you original question was but I'm pretty sure it could be fixed by a fixed place decimal class. Java also has the BigDecimal class which is part of the standard library and could probably serve your needs. Just keep in mind that working with theses classes is slower than their primitive counterparts (float, double).

Something similar to C#'s decimal primitive would be useful. Tracking down small rounding errors with doubles and floats is a huge pain in the rear end.

baquerd
Jul 2, 2007

by FactsAreUseless

dealmaster posted:

Something similar to C#'s decimal primitive would be useful. Tracking down small rounding errors with doubles and floats is a huge pain in the rear end.

I work in the financial industry and we don't even care for internal reports. It's only when you're doing critical code that handles real money transactions that it's really an issue. Most people can just cut it off at output time to whatever precision they want or the horrible, horrible hack:

code:
 double roundedX = ((double)Math.round(x*100)) / 100;
Edit: actually this may not always work... time for me to go to sleep

baquerd fucked around with this message at 18:32 on Aug 1, 2009

trex eaterofcadrs
Jun 17, 2005
My lack of understanding is only exceeded by my lack of concern.

dealmaster posted:

Something similar to C#'s decimal primitive would be useful. Tracking down small rounding errors with doubles and floats is a huge pain in the rear end.

That's all BigDecimal is, the only dumb part is the lack of operator support for that and BigInteger (or all subclasses of Number, honestly). JDK7 was slated to bring operator support for that but, alas, it wasn't meant to be :(

dealmaster
Dec 24, 2005

Somebody call for an exterminator?

quadreb posted:

I work in the financial industry and we don't even care for internal reports. It's only when you're doing critical code that handles real money transactions that it's really an issue. Most people can just cut it off at output time to whatever precision they want or the horrible, horrible hack:

code:
 double roundedX = ((double)Math.round(x*100)) / 100;
Edit: actually this may not always work... time for me to go to sleep

Yeah, the only reason I encountered it was when I was writing the back-end for some life insurance code. Even a penny difference on a 6 or 7 figure settlement or policy would have to be tracked down. It was a monstrous pain in the rear end until I found out that decimal existed. Oh and yeah, that rounding trick doesn't work all the time.

TRex EaterofCars posted:

That's all BigDecimal is, the only dumb part is the lack of operator support for that and BigInteger (or all subclasses of Number, honestly). JDK7 was slated to bring operator support for that but, alas, it wasn't meant to be :(

Yeah it's just too bad there's no primitive that'll do it, but at least they built the functionality into one of their standard library classes. It's just easier for actuaries and non-coders to look at:

code:
decimal x = 100.58;
decimal y = 2.3;
decimal z = x / y;
z += x;
than

code:
BigDecimal x = new BigDecimal(100.58);
BigDecimal y = new BigDecimal(2.3);
BigDecimal z = new BigDecimal( (x.divide(y)).doubleValue() );
z.add(x);

trex eaterofcadrs
Jun 17, 2005
My lack of understanding is only exceeded by my lack of concern.

dealmaster posted:

Yeah it's just too bad there's no primitive that'll do it, but at least they built the functionality into one of their standard library classes. It's just easier for actuaries and non-coders to look at:

code:
decimal x = 100.58;
decimal y = 2.3;
decimal z = x / y;
z += x;
than

code:
BigDecimal x = new BigDecimal(100.58);
BigDecimal y = new BigDecimal(2.3);
BigDecimal z = new BigDecimal( (x.divide(y)).doubleValue() );
z.add(x);

You could always use Groovy. By default fractional numbers are BigDecimals:
code:
def y = 2.3
println y.class
returns

code:
class java.math.BigDecimal
plus it has full operator support for any of java.lang.Number.

Gravity Pike
Feb 8, 2009

I find this discussion incredibly bland and disinteresting.
I'm running out of heap space. To be fair, I'm throwing around a whole lot of aHugeFuckinArrayDeque.clone()'s, but I try to make sure I call aHugeFuckinArrayDeque.clear() before I do that, so I shouldn't have any more than two copies at a time (which I have more than enough RAM for).

Without looking at my rats' nest of code, would you suspect that I'm failing to clear out something somewhere, or is it just Java failing to do garbage collection appropriately? Java's tutorial just says something like "The garbage collector does its job automatically when it determines that the time is right," which isn't really helping me understand what's going on.

rjmccall
Sep 7, 2007

no worries friend
Fun Shoe
There are three possibilities:

1. You have a memory leak. In a GCed environment, this means that you're preventing something from getting collected by holding a reference to it when you don't mean to. We can't help you debug this without looking at your "rats' nest of code", which I assure you no-one wants to do. Try a memory profiler.

2. You're actually doing something which requires a larger resident set than you've configured Java with. I think the default on many platforms is something dinky like 64MB. You can bump this up from the command line (or by configuring your IDE, if you're using one).

3. There's a bug in the garbage collector. This is almost certainly not the problem — not that there aren't bugs in the collector, just that you are very unlikely to be running into one.

Max Facetime
Apr 18, 2009

It's most likely your code. For example, ArrayDeque.clear() is not likely to reduce the capacity of your aHugeFuckinArrayDeque, so if you're holding a reference to the objects somewhere else, calling it is not going to make any memory eligible for garbage-collection.

Gravity Pike
Feb 8, 2009

I find this discussion incredibly bland and disinteresting.

rjmccall posted:

1. You have a memory leak. In a GCed environment, this means that you're preventing something from getting collected by holding a reference to it when you don't mean to. We can't help you debug this without looking at your "rats' nest of code", which I assure you no-one wants to do. Try a memory profiler.

2. You're actually doing something which requires a larger resident set than you've configured Java with. I think the default on many platforms is something dinky like 64MB. You can bump this up from the command line (or by configuring your IDE, if you're using one).

3. There's a bug in the garbage collector. This is almost certainly not the problem — not that there aren't bugs in the collector, just that you are very unlikely to be running into one.

Okay, that's about what I figured. I'm going to start sifting through the code - someone else wrote an extension to my class, and we're both blaming each other for the fuckup. (Of course. :rolleyes:) Thanks.

Ninja Edit: He forgot to set an upper bound to turn on infinite-loop detection, and I failed to pick up on it till now. :doh:

Adbot
ADBOT LOVES YOU

Gravity Pike
Feb 8, 2009

I find this discussion incredibly bland and disinteresting.
I'm trying to create a class that keeps track of different types of costs that a system might incur. (Examples might be time taken, money spent, and incorrect solution penalties.) I'm writing the abstract/template class, and my users need to be able to define their own cost categories at (their) compile time. I thought a good solution would be to have them create an Enum of different cost types, as it would save both time and memory over having cost types represented as strings. I'd like to create my class using generics, but I'm a bit unsure how to proceed.

code:
class CostTracker<E extends Enum> {
   private EnumMap<E,Float> costs = new EnumMap<E,Float>;
   public void set(E type, Number cost) {
      costs.put(E, cost.toFloat());
   }
   public float sum() {
      float retval = 0;
      for (E type : costs.keySet()) {
         retval+=costs.get(type);
      }
      return retval;
   }
}
And the user would do something like:
code:
enum MyCostTypes {
   TIME,MONEY
}
CostTracker<MyCostTypes> = new CostTracker<MyCostTypes>();
Is this correct? Is this a bad way of doing things?

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