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
Carbon dioxide
Oct 9, 2012

As the guy points out, the main thing that will break is frameworks (and other programs) that make use of internal java.* or sun.misc.* stuff that was explicitly made to stay internal because abusing it might gently caress up things. The classes that were never meant to be accessible but could be reached anyway are now truly locked away.

Apparently a few commonly used frameworks made use of that, so they'll need to update their stuff.

I'm surprised, he said sun.misc.Unsafe will stay accessible, I had heard before it wouldn't. Unsafe is this unusual class that's full of native methods that allow you to access memory pointers, to direct memory manipulation, and to instantiate classes without calling their constructors. It's not supposed to be accessible, but outside classes can access it by reflection and use it for performance optimizations. However, because it allows for direct memory manipulation, Unsafe is rather unsafe.

I suppose Oracle got so many complaints from people using Unsafe that they decided to keep it accessible.

Adbot
ADBOT LOVES YOU

Cheesus
Oct 17, 2002

Let us retract the foreskin of ignorance and apply the wirebrush of enlightenment.
Yam Slacker
What are some good resources to investigate for code/methodology optimization and/or "just use Java correctly"?

I have a mature platform (I'm not doing premature optimization) and under certain loads the garbage collection goes bonkers and the process usage spikes CPU. A toe dipping into heap investigation shows that it may be abusing stuff like String an obscene amount.

But it's just an educated guess based on a little time googling around. What books, web sites, tools should I be looking at to continue this journey?

Methanar
Sep 26, 2013

by the sex ghost
I think I figured it out

Methanar fucked around with this message at 23:02 on Aug 29, 2016

Zaphod42
Sep 13, 2012

If there's anything more important than my ego around, I want it caught and shot now.

Methanar posted:

Hi, I'm not a programmer whatsoever but I need to do some programming anyway. I've got the Node.JS serialport library (don't actually know if it's a library) to work with.

Javascript and Java are actually completely unrelated languages.

Most Arduino code is written in C++, though you can use that Node.JS if you want. Either way... this is probably the wrong thread.

Try the Javascript thread for Node.js.

Methanar posted:

How do I even begin.

You're probably going to have to learn programming. Its not super crazy hard, but just jumping in to "how do I" without understanding the background means you're not really going to understand it or be able to do much. You're just asking for people to do it for you at that point.

Zaphod42 fucked around with this message at 20:39 on Aug 29, 2016

Paul MaudDib
May 3, 2006

TEAM NVIDIA:
FORUM POLICE
I'm using a Spring project with Hibernate. I have the SessionFactory in a bean because I'm using Spring to define some beans as @Transactional and injecting the Hibernate session.

I'd like to have a generic "application config" properties file that will contain the database parameters rather than building them into the application. However since I am using an XML-based configuration I can't also do programmatic configuration (AFAIK).

I'm thinking something like extending the LocalSessionFactoryBean class and overriding the setHibernateProperties method to add some additional parameters that I pull from a static class? Or is there a better way?

[insert grayscale As Seen On TV gif here]

FateFree
Nov 14, 2003

If you are using Spring you should be using dependency injection, which is the entire point of spring. That would mean putting your properties in a properties file and injecting them into your beans with your xml configuration. If this is a new project though you should really be using Spring boot, which makes all of this a million times easier.

Volguus
Mar 3, 2009
And don't forget about spring-data-jpa. Makes working with JPA entities/repositories embarrassingly easy.

Jo
Jan 24, 2005

:allears:
Soiled Meat
I could use some help in designing things the new JavaFX way.

I've got an application which does/will do the following:

  1. User adds a series of streams from files in the UI.
  2. Application seeks through streams and synchronizes them.
  3. Application determines intrinsic camera parameters from the streams.
  4. Using eigenbackgrounds and carving, figure volume is extracted.
  5. Using skeletonization, bones are recovered.

I have, in general, three types of data, the image stream data (along with relative offsets from the earliest stream and a background pattern), the camera parameters, the recovered volume, and the recovered skeleton.

In JavaFX, I have the MainWindowController which I was hoping to use to drive all the UI elements with nice, snazzy callbacks and listeners, then have the Main application do all the heavy lifting. Here's where I'm running into problems: it looks like the MainWindowController can't reference the Main Application's properties unless I pass a reference to it or make them static. Both seem like really crappy design. I'm not sure how I'd do the separation of concerns.

This mock layout might help explain a bit better:



I'll have the n-synchronized streams selected (and, ideally, scrubbable), a tab for the silhouette extraction, and a tab for the mesh recovery. If this were a Swing application, I imagine I'd just be adding a lot of listeners and callbacks in the main startup function, but I'd like to be slightly more graceful this time if I can be. Anyone have a recommendation for how they'd structure an application like this?

===

Okay, so I've got a bit of an update. Had some time to think and I'm going with this:

I'll give the main model the static reference to media files and most of the main application logic. I'll let the FXML handle all the UI stuff since I'm going to be putting most of the UI in there anyway. I've done some prototyping and it looks like the code is pretty clean. Lots of observers and listeners, but on the whole it's good stuff.

Jo fucked around with this message at 04:22 on Aug 31, 2016

Sagacity
May 2, 2003
Hopefully my epitaph will be funnier than my custom title.

Volguus posted:

And don't forget about spring-data-jpa. Makes working with JPA entities/repositories embarrassingly easy.
And embarrassingly hard to optimize, I've found. I've fallen into the JPA trap multiple times, thinking each time "it must have been improved by now". But I always end up having to change my domain objects to suit the requirements of JPA and dropping down to low-level criteria APIs in order to force Hibernate to generate *juuuuust* the right type of query so that Oracle doesn't mess up its query plan.

How have you dealt with this?

Boz0r
Sep 7, 2006
The Rocketship in action.
I'm trying to find out how this Grails stuff works. I've made a new project in IntelliJ, but when it runs its setup scripts and stuff, it throws me an error, even though I haven't touched anything yet:

code:
"C:\Program Files (x86)\Java\jdk1.8.0_65\bin\java" -Dgrails.home=C:/tools/grails-1.2.5 "-Dtools.jar=C:\Program Files (x86)\Java\jdk1.8.0_65\lib\tools.jar" -Dgroovy.starter.conf=C:/tools/grails-1.2.5/conf/groovy-starter.conf -Djline.WindowsTerminal.directConsole=false -Dfile.encoding=windows-1252 -classpath C:\tools\grails-1.2.5\lib\groovy-all-1.6.8.jar;C:\tools\grails-1.2.5\dist\grails-bootstrap-1.2.5.jar org.codehaus.groovy.grails.cli.support.GrailsStarter --main org.codehaus.groovy.grails.cli.GrailsScriptRunner --conf C:/tools/grails-1.2.5/conf/groovy-starter.conf "create-app grailstest2 --inplace"
Welcome to Grails 1.2.5 - [url]http://grails.org/[/url]
Licensed under Apache Standard License 2.0
Grails home is set to: C:/tools/grails-1.2.5

Base Directory: C:\grailstest2
Resolving dependencies...
Dependencies resolved in 972ms.
Running script C:\tools\grails-1.2.5\scripts\CreateApp_.groovy
Error executing script CreateApp: No signature of method: java.lang.Boolean.toBoolean() is applicable for argument types: () values: []
groovy.lang.MissingMethodException: No signature of method: java.lang.Boolean.toBoolean() is applicable for argument types: () values: []
	at _GrailsSettings_groovy.run(_GrailsSettings_groovy:74)
	at _GrailsSettings_groovy$run.call(Unknown Source)
	at _GrailsClasspath_groovy$run.call(Unknown Source)
	at _GrailsClasspath_groovy.run(_GrailsClasspath_groovy:32)
	at _GrailsClasspath_groovy$run.call(Unknown Source)
	at _GrailsEvents_groovy$run.call(Unknown Source)
	at _GrailsEvents_groovy.run(_GrailsEvents_groovy:30)
	at _GrailsEvents_groovy$run.call(Unknown Source)
	at _GrailsClean_groovy$run.call(Unknown Source)
	at _GrailsClean_groovy.run(_GrailsClean_groovy:29)
	at _GrailsClean_groovy$run.call(Unknown Source)
	at _GrailsPlugins_groovy$run.call(Unknown Source)
	at _GrailsPlugins_groovy.run(_GrailsPlugins_groovy:28)
	at _GrailsPlugins_groovy$run.call(Unknown Source)
	at _GrailsCreateProject_groovy$run.call(Unknown Source)
	at _GrailsCreateProject_groovy.run(_GrailsCreateProject_groovy:28)
	at _GrailsCreateProject_groovy$run.call(Unknown Source)
	at CreateApp_.run(CreateApp_:25)
	at CreateApp_$run.call(Unknown Source)
	at gant.Gant.processTargets(Gant.groovy:494)
	at gant.Gant.processTargets(Gant.groovy:480)
Error executing script CreateApp: No signature of method: java.lang.Boolean.toBoolean() is applicable for argument types: () values: []
What did I do wrong?

Volguus
Mar 3, 2009

Sagacity posted:

And embarrassingly hard to optimize, I've found. I've fallen into the JPA trap multiple times, thinking each time "it must have been improved by now". But I always end up having to change my domain objects to suit the requirements of JPA and dropping down to low-level criteria APIs in order to force Hibernate to generate *juuuuust* the right type of query so that Oracle doesn't mess up its query plan.

How have you dealt with this?

I have never had to "change my domain objects to suit the requirements of JPA". I mean, maybe i did and i just don't know it. Can you give me an example?
As for query optimization, for that query that was badly generated but its run 100 times per second, yea, you may have to get dirty. Criteria API, make a view and an entity on top of that or in extreme cases, native SQL. But, on a reasonably sized project that doesn't happen very often. On a 10 year old project with over 10 millions of lines of code, yea, it can happen a few times.

Sagacity
May 2, 2003
Hopefully my epitaph will be funnier than my custom title.

Volguus posted:

I have never had to "change my domain objects to suit the requirements of JPA". I mean, maybe i did and i just don't know it. Can you give me an example?
Sure! A simple example is a very basic setup of orders and order lines we have. Nothing special, "order" has a List of "order lines".

In order to get this to work properly I had to:
  • Change the List into a Set, because otherwise when retrieving the orders Hibernate would, because we're joining a few other tables as well, give me duplicate lines. This is a known issue but still. This was especially annoying because some of the order lines in an order can be identical before persisting. After persisting this is fine, since they can be distinguished by id, but now I need to add some kind of synthetic id when creating them just to be able to insert them into a Set.

  • I needed to add an "owner" field in the order line that refers back that to the order. I don't need this for any business logic, but if I don't add it then Hibernate will do redundant queries. When saving the order it will properly save the line, but then it will immediately do an UPDATE for each line, setting the id of the order line to.... the id of the order line :shrug: Adding this "owner" field solves this but, again, this is not really explained anywhere and it seems like something I shouldn't have to do.

M31
Jun 12, 2012
Choosing a Set to solve the first problem looks like the wrong solution. From the description it looks like it would still query too much data, but just discard it afterwards. How large this problem is depends on the average number of order lines. Also, can't you just override equals = false when id == null to avoid the Set problem?

My experience with JPA is that as soon as you start using it you should just forget you are using a database. As soon as your queries get more complex than a simple select with one or two where clauses you should consider using something else. Maybe keep JPA for updates only (fetch by id + update, taking advantage of JPA's session cache).

JPA has lots of unexpected behaviour (at first glance at least) and you can forget about using more advanced database features. Also, the object mapping, which is probably what most people use it for, is handled just as well by something like QueryDSL in my opinion.

FateFree
Nov 14, 2003

M31 posted:

JPA has lots of unexpected behaviour (at first glance at least) and you can forget about using more advanced database features. Also, the object mapping, which is probably what most people use it for, is handled just as well by something like QueryDSL in my opinion.

I thought QueryDSL with their Predicate library was the perfect solution for queries, except I started noticing all of these N+1 selects popping up because those queries don't have any fetch strategy hints. I guess I wish JPA had a fetch strategy annotation for this purpose.

Sagacity
May 2, 2003
Hopefully my epitaph will be funnier than my custom title.

M31 posted:

Choosing a Set to solve the first problem looks like the wrong solution. From the description it looks like it would still query too much data, but just discard it afterwards. How large this problem is depends on the average number of order lines. Also, can't you just override equals = false when id == null to avoid the Set problem?
Sure, but that's equally broken though, isn't it? Then your domain objects are equal unless some magic field is not set. By the way, the Set<> it uses is not just a regular set, it's actually a Hibernate-specific implementation of a Set which it has all sorts of knowledge of. It actually doesn't query too much, so that's good I guess.

M31 posted:

My experience with JPA is that as soon as you start using it you should just forget you are using a database. As soon as your queries get more complex than a simple select with one or two where clauses you should consider using something else. Maybe keep JPA for updates only (fetch by id + update, taking advantage of JPA's session cache).

JPA has lots of unexpected behaviour (at first glance at least) and you can forget about using more advanced database features. Also, the object mapping, which is probably what most people use it for, is handled just as well by something like QueryDSL in my opinion.
That's mostly what we're doing now. Just using the @Query annotations in Spring Data to do custom queries for whenever JPA trips over itself. QueryDSL is nice but annoyingly it doesn't play nicely together with JPA annotations if you want to generate a metamodel from that (it wants to do this build-time using a connection to your actual database instead). IMHO we should've just gone with QueryDSL or JDBI from the start. Oh well.

M31
Jun 12, 2012

FateFree posted:

I thought QueryDSL with their Predicate library was the perfect solution for queries, except I started noticing all of these N+1 selects popping up because those queries don't have any fetch strategy hints. I guess I wish JPA had a fetch strategy annotation for this purpose.

I don't know about any annotations, but you can use .fetchJoin() in QueryDSL on JPA.

Sagacity posted:

Sure, but that's equally broken though, isn't it? Then your domain objects are equal unless some magic field is not set.
Yeah, maybe? If the id is just there to please Hibernate then everything is already hopeless. If the id is required in your domain object, than having an object without an id is already kind of a weird situation. I think adding a special case to equals in that situation is less magic than creating a dummy id though.

Sagacity
May 2, 2003
Hopefully my epitaph will be funnier than my custom title.

M31 posted:

I think adding a special case to equals in that situation is less magic than creating a dummy id though.
Fair enough. I'm not sure if I'm running into a "grass is greener" kind of situation with JPA vs JDBI, it probably has enough horrors as well.

PierreTheMime
Dec 9, 2004

Hero of hormagaunts everywhere!
Buglord
Is there a decent way to compute how much memory an application should consume and how to improve efficiency? I've been writing some tools to convert plaintext to objects via an API and while it works great for a small-moderate number of conversions it appears to draw enough memory on 240 passes in a single run to crash and throw a NoClassDefFoundException. I didn't even think this would be a possibility since the text in question is like 20k tops and I assumed garbage collection would clear out old objects after they went out of use.

PierreTheMime fucked around with this message at 00:34 on Sep 7, 2016

Paul MaudDib
May 3, 2006

TEAM NVIDIA:
FORUM POLICE
OK, more Spring questions.

Let's say that I want to have the ability to configure either a SQLite or a Postgres DB at runtime (or test-time). Do I just include both the SQLite and Postgres drivers, and then set up a properties-placeholder file that injects the appropriate class-name into the datasource/hibernate beans?

What if I didn't want to package both the JARs in it? Is there a way to declare a folder that will get injected at runtime? Or is that something that would have to be done through the JVM settings?

Now that I've got a handle on it Spring seems super nice and is a super easy way to inject stuff for testing. It's annoying how many "magic" words there are ("oh, you didn't declare a MultiPartResolver bean? no uploads for you") but once you're used to just having components just magically appear then composition becomes real easy.

Paul MaudDib
May 3, 2006

TEAM NVIDIA:
FORUM POLICE

PierreTheMime posted:

Is there a decent way to compute how much memory an application should consume and how to improve efficiency? I've been writing some tools to convert plaintext to objects via an API and while it works great for a small-moderate number of conversions it appears to draw enough memory on 240 passes in a single run to crash and throw a NoClassDefFoundException. I didn't even think this would be a possibility since the text in question is like 20k tops and I assumed garbage collection would clear out old objects after they went out of use.

How much memory are we talking? The JVM has some super low limits by default (like 256 MB per VM) but it's also possible that you are doing something that results in exponential memory consumption (strings are terrible about this unless you're aware). Be sure that you aren't going too nuts with string appending, use StringBuilder if you aren't already. Also be sure that you are dropping all references to an object after you are done using it - if it's still hanging around in a list somewhere or something else that is in-scope, it cannot be garbage collected. Keep variables local to a function as much as possible and it becomes automatic.

If you are totally stuck, you can just use something like SaxParser or Jackson, if you can convert your data into XML or JSON objects. Or if you have CSV there is an Apache CSV library out there.

Paul MaudDib fucked around with this message at 02:44 on Sep 7, 2016

CPColin
Sep 9, 2003

Big ol' smile.

Paul MaudDib posted:

use StringBuffer

Or StringBuilder, so you don't waste processing time on unnecessary thread safely.

Paul MaudDib
May 3, 2006

TEAM NVIDIA:
FORUM POLICE

CPColin posted:

Or StringBuilder, so you don't waste processing time on unnecessary thread safely.

Whoops, fixed.

PierreTheMime
Dec 9, 2004

Hero of hormagaunts everywhere!
Buglord
I am concatenating a decent number of Strings along the way, but no more than a dozen per object. I'll convert them all to StringBuilder and see if it makes a difference. I'm sure it's an issue with my garbage-tier code, I was just surprised that such relatively simple stuff hit the default memory limit. I haven't tried expanding the limit yet, wanted to see about reducing unnecessary load first.

CPColin
Sep 9, 2003

Big ol' smile.
There are tools that let you profile memory usage and inspect the heap and stuff, but I have no idea which ones are "good" these days.

PierreTheMime
Dec 9, 2004

Hero of hormagaunts everywhere!
Buglord
After a lot of research and refactoring considerations, it turns out the server was just massively overloaded at the time. :shrug: Reran the same process this morning and it worked great in half the time.

Good learning experience, I suppose.

weas
Jul 22, 2007

Tougher than the
toughest tough guy

Paul MaudDib posted:

OK, more Spring questions.

Let's say that I want to have the ability to configure either a SQLite or a Postgres DB at runtime (or test-time). Do I just include both the SQLite and Postgres drivers, and then set up a properties-placeholder file that injects the appropriate class-name into the datasource/hibernate beans?

What if I didn't want to package both the JARs in it? Is there a way to declare a folder that will get injected at runtime? Or is that something that would have to be done through the JVM settings?

Now that I've got a handle on it Spring seems super nice and is a super easy way to inject stuff for testing. It's annoying how many "magic" words there are ("oh, you didn't declare a MultiPartResolver bean? no uploads for you") but once you're used to just having components just magically appear then composition becomes real easy.

My applications all run integration tests against an HSQLDB at test time and then run on Oracle in production. Dependencies in the test scope are not included with the final package, so for your test database driver, just put it in the "test" scope in your pom.xml (I am sure gradle has an equivalent option if that's what you use):

code:
<dependency>
	<groupId>org.hsqldb</groupId>
	<artifactId>hsqldb</artifactId>
	<scope>test</scope>
</dependency>

<dependency>
	<groupId>com.oracle</groupId>
	<artifactId>ojdbc6</artifactId>
	<version>11.2.0.3.0</version>
</dependency>

FateFree
Nov 14, 2003

Paul MaudDib posted:

OK, more Spring questions.

Let's say that I want to have the ability to configure either a SQLite or a Postgres DB at runtime (or test-time). Do I just include both the SQLite and Postgres drivers, and then set up a properties-placeholder file that injects the appropriate class-name into the datasource/hibernate beans?

Now that I've got a handle on it Spring seems super nice and is a super easy way to inject stuff for testing. It's annoying how many "magic" words there are ("oh, you didn't declare a MultiPartResolver bean? no uploads for you") but once you're used to just having components just magically appear then composition becomes real easy.

Also you should be using Profiles to change configurations depending on the environment, again if you are using Spring boot this is all very easy because it will look for an application-dev.properties file if the current profile is dev, or an application-prod.properties file for a production profile. And again if you use spring boot you'll get support for most functions right out of the box without you having to do anything. You really really should be using it, its got some great documentation as well.

Defenestrategy
Oct 24, 2010

So, I got this java project where I have to 1) make an array of N random numbers, 2) Use bubble sort to sort it, and 3) time how long it would take the program to do it X number of times. It compiles, but all it does is scream at me it sorted a thing forever and ever and ever even though I expect it to do it once for one sort. If anyone has advice I'd be grateful. Sorry about the formatting. I'm a terrible person.


code:
import java.util.Scanner;
public class thing2 {

	public static void main(String[] args) {
	
	 Scanner scan = new Scanner(System.in);
	 int runTime = 0;
	 int x = 0;
		 
	 System.out.println("How many items in your array?");
	 int n = scan.nextInt();
	 System.out.println("How many iterations?");
	 int num_i = scan.nextInt();
	 
	 
	 do{
		 int timeS = (int) System.currentTimeMillis();
				 
		  int i = 0;
			 int[] anArray;
			 anArray = new int[n];
			 

			 do {	anArray[i] = (int) (Math.random()*100);
					i++;
					} while (i < n );

						 
			    int j;
				boolean flag = true;
				int temp;
				
				while (flag){
			    flag = false; 
			    for ( j=0; j < anArray.length -1; j++)
			    {
				 if (anArray[j]<anArray[j+1])
				 {
					 temp = anArray[j];
					 anArray[j] = anArray[j+1];
					 anArray[j+1] = temp;
					 flag = true;
				 }
			         
	 		 	 } 
	 }
				System.out.println( "I sorted a thing!");
			     
				int timeE = (int) (System.currentTimeMillis() - timeS);
                runTime = runTime + timeE;
				
	 } while( x <= num_i);
	 

}
}		

Defenestrategy fucked around with this message at 21:43 on Sep 8, 2016

Data Graham
Dec 28, 2009

📈📊🍪😋



Put some more prints in so you can see which loop it's getting stuck in and why.

baka kaba
Jul 19, 2003

PLEASE ASK ME, THE SELF-PROFESSED NO #1 PAUL CATTERMOLE FAN IN THE SOMETHING AWFUL S-CLUB 7 MEGATHREAD, TO NAME A SINGLE SONG BY HIS EXCELLENT NU-METAL SIDE PROJECT, SKUA, AND IF I CAN'T PLEASE TELL ME TO
EAT SHIT

Or step through with a debugger if you can

Also while loops are good for stuff where you need to check if a condition has changed, like you're doing with your sorting flag. Generally if you're going to loop over some stuff a fixed number of times, you should just use a for loop instead of janitoring your own iteration counter

Defenestrategy
Oct 24, 2010

Data Graham posted:

Put some more prints in so you can see which loop it's getting stuck in and why.

It appears that it's looping the entire thing over and over again. Which doesn't make any sense, since I have it set so that it does it while x <= num_i ....?

Data Graham
Dec 28, 2009

📈📊🍪😋



So when does x change?

Defenestrategy
Oct 24, 2010

Data Graham posted:

So when does x change?

I forgot to increment x :smithicide:.

edit: and now it's doing it correctly super thanks!

Data Graham
Dec 28, 2009

📈📊🍪😋



'Scool, that's why this was a valuable exercise :)

baka kaba
Jul 19, 2003

PLEASE ASK ME, THE SELF-PROFESSED NO #1 PAUL CATTERMOLE FAN IN THE SOMETHING AWFUL S-CLUB 7 MEGATHREAD, TO NAME A SINGLE SONG BY HIS EXCELLENT NU-METAL SIDE PROJECT, SKUA, AND IF I CAN'T PLEASE TELL ME TO
EAT SHIT

That's also why you just use a for loop unless you have a good reason not to :v:

EmmyOk
Aug 11, 2013

If you know the definitive bounds then there is no reason not to use a for loop, if you need to find an element but don't know how big the boundary is use a while loop, and a do while if you need to guarantee the loop runs at least once no matter what.

e: To clarify on while loops I mean something like searching for the nth prime when you don't know what range the nth prime is in.

FateFree
Nov 14, 2003

Ya know I don't think I've ever written a do-while loop in the past 15 years of coding haha.

scissorman
Feb 7, 2011
Ramrod XTreme
I'm one of several developers working on a GWT webapp running in a Tomcat container and I'm looking at how to replace our currently hardwired code with a more loosely coupling using dependency injection.
The main objects I want to change are things like user and session managers, which are created once and then kept for the rest of the application's lifetime.
Right now they're implemented as singletons, which makes writing isolated tests and cleaning up the codebase harder than it needs to be.
I've been looking at different frameworks like Spring, Weld and Guice but they seem way more complicated than what I need.
Is there a more lightweight solution you can recommend instead?

FateFree
Nov 14, 2003

Spring is only as complicated as you want it to be. It can be daunting because it has grown so big, but the truth is you can use a tiny subset of spring and it's very lightweight. Chances are you can use other features from it down the line, but I would recommend you start out with just the dependency injection.

With spring boot it's even easier to get started as I've said a bunch of times before. But in this day and age it's almost required to know how to use spring because it's so valuable. Just read the docs, they are very informative!

Also not sure what you meant about singletons, they are used everywhere in spring and other frameworks but it doesn't affect testing in any way.

Adbot
ADBOT LOVES YOU

Gravity Pike
Feb 8, 2009

I find this discussion incredibly bland and disinteresting.

FateFree posted:

Also not sure what you meant about singletons, they are used everywhere in spring and other frameworks but it doesn't affect testing in any way.

Are you statically referencing the singleton implementation instead of passing it as a constructor/setter parameter? You can change that right away, before you even get to injecting.

We're using HK2 right now, since it comes with grizzly, and we're pretty happy with it. I also hear good things about modern spring, although it was a xml-laden nightmare the last time I used it professionally.

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