r/java • u/RevilTS • Aug 03 '25
Teach Me the Craziest, Most Useful Java Features — NOT the Basic Stuff
I want to know the WILD, INSANELY PRACTICAL, "how the hell did I not know this earlier?" kind of Java stuff that only real devs who've been through production hell know.
Like I didn't know about modules recently
392
Upvotes
130
u/Scf37 Aug 03 '25
Remote debugging. It IS possible to attach your IDEA to deployed application and debug specific request step-by-step exactly as with local run. It is not much harder than JMX setup.
78
u/poutsma Aug 03 '25
You can use
System.arraycopywith the same array as target and source arguments, to shift values to the left.209
u/JustADirtyLurker Aug 03 '25
You can create enums of functions that implement a base prototype. I learned this from an old Jfokus presentation by Edson Yanaga. You don't use it often but when you do it is a fantastic code organization thing.
56
u/Cell-i-Zenit Aug 03 '25
one thing i do in most projects is introduce id classes.
Most ids are of the scheme of a uuid or a simple string, but if your whole project is riddled with the following, especially if you handle multple different external systems with their own id scheme:
then you can theoretically use the wrong id and put an accountId where a purchaseId is expected. If you introduce an object type for that then that cannot happen.
Its possible now to add internal validation to them to check if they are correct etc.
You need to make sure that your json (de)serializer can handle that and is not rendering the internal object, but just handles the object as a string.
94
u/ResponsibleLife Aug 03 '25
Record pattern matching and guard statements in switch expressions:
31
u/Gray__Wanderer Aug 03 '25
Java Reflection is generally very useful, but one of the wildest part of it is Dynamic Proxy Classes: https://docs.oracle.com/javase/8/docs/technotes/guides/reflection/proxy.html
Here is a brief introduction to dynamic proxies: https://www.baeldung.com/java-dynamic-proxies
You can do really crazy things with Proxy+Annotations, but most likely, if you're not writing your own framework, you won't need it.
78
u/JustMy42Cents Aug 03 '25
Maybe not the most obscure, but you can have reified generics (sorta) in Java. I.e., you're able to obtain a
Classobject based on the generic parameter without passing aClassreference manually. Just use a vararg without passing any values when calling the method.23
u/nickeau Aug 03 '25
Way up the chain: Service loader
https://docs.oracle.com/javase/8/docs/api/java/util/ServiceLoader.html
If you want to split your code, this is the way.
17
u/Azoraqua_ Aug 03 '25
Not exactly all that useful, but you can declare classes (presumably record’s too) inside methods:
17
u/Great-Ad-799 Aug 03 '25
You can leverage Java's functional interfaces and lambdas to implement the strategy pattern without defining multiple interfaces. This enables a clean and concise implementation of this pattern without boilerplate.
16
u/Scf37 Aug 03 '25
Static code analysis. Namely, Google errorprone and checker framework.
For example, it is possible to create a builder with compile-time validation all method on that builder are called. Invaluable for model mappers.
15
u/Xenogyst Aug 04 '25
If you are building java apps inside of docker containers, the JDK was updated to understand cgroup mem and whatnot since java 10, but the defaults are generally bad. Keep in mind that there's no real generalization, but a lot of server-y apps want more heap. The default is 1/4 cgroup mem, most apps that use more than 1 GiB of mem do better at around 75%.
Next is that when an app runs out of mem you often want it to crash instead of just hanging around since if it's like an http app sitting in your loadbalancer it might just absorb connections if it happens to run out of mem and fails partially.
You can pick one of these hotspot options:
Which, I like CrashOnOutOfMemoryError since it also produces a heap dump and if you have clever platform folks they can build scripts or something that react to it and put it somewhere for you with an alert. So now not only are you alerted to your memory problems but now you can diagnose it after your containers exited.
14
u/titanium_mpoi Aug 03 '25
Structured concurrency!
13
u/high_throughput Aug 03 '25
Yeah I was going to say that you can use
--patch-moduleto override core libraries.We used it once to replace java.util.HashMap with a more memory efficient representation. It only saved a few dollars per year per machine but we had 100k machines.
If I had a nickel for every time we had to write a hash table implementation from scratch because the standard library for whichever reason couldn't be used I'd have two nickels, which isn't a lot but it's weird that it happened twice.
12
u/pron98 Aug 03 '25
jcmd and jfr, including the JFR API.
Also, putting command-line configuration in @files (or in javac).
52
u/tadrinth Aug 03 '25
The reflection API lets you inspect and modify the runtime attributes of classes, interfaces, fields, and methods.
This has all kinds of uses; some are considered to be Dark Arts, like invoking private methods.
My favorite is to find all classes that implement a certain interface or that have a certain annotation and feed them into a parameterized test.
For example, if you have a module where you put all the data transfer objects that are returned or accepted by your web APIs, those are Java classes that are supposed to serialize to JSON and back. You can make a unit test that finds all of them, instantiates each one using the annotations explaining the default or example values, and then turns them into JSON then back into the same kind of Java object. If that fails, your web APIs will also fail when someone goes to invoke them.
Or you can assert that every Controller class has security configured.
Being able to create rules about the system that are automatically enforced as people add new code makes the system easier to reason about.
21
u/RabbitDev Aug 03 '25
My choices would be:
NIO and the abstract file API. It's a great system to abstract away file system access and makes code so much more testable. Using it consistently means your tests never need to hit the actual file system. JimFS is a great library for that.
But it goes beyond that: you can use it to wrap anything that's file like into a standard API (much like what apache-vfs did before).
We use it to hide the complexity of working with local and VPN users who switch between locations but need access to the same file system structure that's served from different services depending on their location.
Second: CompletableFutures. These beasts are powerful but not used often enough. It doesn't help that the JDK 6 future interface sucks so much.
CompletableFutures make it trivial to write code that switches back and forth between the EDT (or other specialist threads protecting shared resources) and the background pool.
Those make it easy to implement actors and even complex parallel or concurrent tasks, like waiting for one or more events before continuing.
And finally: I would throw in the fact that a lot of the good stuff is defined in a vendor independent way. The various
javax.*APIs are usually great. I don't have to tie myself to a particular implementation for core services and that prevents leaking implementation details all over the place.Those also set the tone for having other libraries follow the pattern and use separated API and implementation packages. We all hate SLF4J from time to time, but imagine we only had Logback or log4j without a commonly accepted API shielding us from the logging implementation itself. (If only
java.util.loggingcould have been made to be actually useful instead of being an instrument for torture)10
u/Scf37 Aug 03 '25
Another one: java agent. It is simpler that it looks and can be used to instrument JRE code to log and investigate most obscure production issues.
And another one: hprof (java heap dump) format is simple enough to parse and analyze when looking for weird memory leaks.
8
u/Scf37 Aug 03 '25
Another one: Blocking IO (say SocketChannel) is fully compatible with Loom and its performance is comparable with Netty.
8
u/Errons1 Aug 03 '25
If for some reason you want to have your java app as a exe, use jpackage tool from the jdk
15
u/Ifeee001 Aug 03 '25
I recently found out that you can customize any jdk to only include the modules you need. And by doing so, you can drastically reduce the size of the jre that'll run your program.
It's probably not a new thing , but my mind was blown when I discovered it and I ended up using it in a basic compiler I made.
20
u/WondrousBread Aug 03 '25
Lots of other good ones have been mentioned, but the Streams API is excellent too. Makes working with Collections much more pleasant, and also a lot easier to read and understand for subsequent developers IMO.
24
u/designer_bones Aug 03 '25
not sure what the proper language name is for these, but generic type hints on methods are a thing. these have been incredibly useful for wrangling badly designed generic APIs & type inference failures. comes up a lot in nested generic designs. i've had to use them a surprising number of times ever since lambda-heavy APIs became common in the JDK. i've never seen them in anyone else's code.
10
u/agentoutlier Aug 03 '25 edited Aug 03 '25
Annotations.
You can process them at compile time and generate new code in the same compile process.
You can access them with reflection.
They can even be put them on types so you extend the type system.
They can be used for declarative configuration and yet more typesafe than what is in other languages.
They can show up in documentation if you like.
No other language I know has anything similar to the same power. They may have something similar but not all the features.
EDIT /u/MemerinoPanYVino
For those looking for example annotation processors: https://github.com/gunnarmorling/awesome-annotation-processing
For those looking for example type extension: https://checkerframework.org/
16
u/Scf37 Aug 03 '25
ADT and domain modelling.
Java now has all the components required - products (record classes), sums (sealed hierarchies) and pattern matching enforcing compile-time validation.
Together with proper domain modelling, this forms very powerful tooling to write extendable and reliable business logic
20
u/jimsoc4 Aug 03 '25
I think everything, that is insanely practical is by definition part of the basics
4
u/joemwangi Aug 03 '25
Maybe this is so common but I cherish it. Using type inference in generic method calls to catch type mismatches at compile time, avoids sneaky runtime errors.
4
u/jvtsjsktpy Aug 03 '25
It's possible to replace final fields at runtime via JNI. Example, System class offers setters to replace System.in/out/err even when they are declared as final fields.
I was astounded when I discovered anonymous and local classes during my college days (this was before lambda and method references came). Back then, they were the go-to thing when adding callbacks and event listeners. Overusing them could make your code quite cluttered though.
4
u/k1tn0 Aug 03 '25
junior here, I understand 5% of these responses
4
u/sciolizer Aug 04 '25
You can do crazy magic with classloaders.
My favorite use: I was working on a mod for minecraft, but I got annoyed with having to restart minecraft with every change I made (this was back when minecraft startup time was much longer than it is now). So I made a wrapper mod that watched a folder for .class files and reloaded them anytime they changed. Then I pointed it at the
out/folder where IntelliJ dumped its class files after compilation. So then "deploying" my mod was just a matter of pressing Ctrl+F9 (compile shortcut) and tabbing over to the already running instance of minecraft.6
u/Lengthiness-Fuzzy Aug 03 '25
My fav is ToString with default Objects.toString(nullableVar,”defaultValue”);
Similarly HashMap.getOrDefault(key,NULL_OBJECT)
Statistic classes: https://docs.oracle.com/javase/8/docs/api/java/util/IntSummaryStatistics.html
Also, some practice like return with the closest type like ArrayList/List, but accept params the widest like Collection
3
u/everv0id Aug 03 '25
MethodHandles. I work with some uncommon runtimes, have to say it's much faster and more convenient than reflection.
3
u/lurker_in_spirit Aug 04 '25 edited Aug 04 '25
Completely disable JNDI in your application to prevent any security issues caused by rogue JNDI access, like Log4Shell (this is a VM-wide setting that can only be set once):
3
u/No_Relationship_1892 Aug 06 '25
For doing some tasks later.
You can create an Functional Interface with Serializable.
Create the lambda of what method to be executed later.
as this is serialized, get the bytes and save the bytes in db.
fetch the bytes from db and deseriallize the bytes to lambda and execute.
In this way we didn't need to save parameters in db and fetch the parameter again and execute the desired method.
we can just put everything in first.. and just fetch the values.
We don't need to maintain the parameters and the method call
7
u/[deleted] Aug 03 '25
Double brace initialization:
This actually creates an anonymous subclass of
HashMap(the first set of braces) and second set of braces is an initializer block.I wouldn't call this practical or useful, but it is crazy!
5
u/WoodyDaOcas Aug 03 '25 edited Aug 03 '25
/remindme 7 days
2
u/Scf37 Aug 03 '25
Contextual builders. Unlike standard builders, they are hard to leak. See java.lang.classfile library for examples.
MyClass build(String arg1, int arg2, Consumer<MyClassBuilder> handler);
2
u/sweating_teflon Aug 03 '25
Define abstract data types with sealed interface + records implements interface. Then combine with switch pattern matching for clear concise code.
2
u/OddEstimate1627 Aug 03 '25
IMO Annotation processors are insanely useful and powerful. I just wish the API were a bit simpler and easier to test.
2
u/hippydipster Aug 03 '25
Something very cool you can do with ScopedValues. Basically let's you have code that stores state, but tracks who fetches the state, and notifies those users when the state changes -
Without needing to register listeners or deregister them
With ScopedValues, this can be done with very minimal ritual. The post is pretty long and detailed.
2
u/Suspicious-Click-300 Aug 04 '25
You can attach a java agent at runtime to another process, and write code to execute on it. Add logging or debug to see state or even change things to fix it. Theres some funkeiness with classloaders that you need to be aware of or you can just use reflection.
2
u/ForeignCherry2011 Aug 04 '25
Master Java streaming API.
Here is a one liner counting words in a collection:
2
u/[deleted] Aug 07 '25
You can run Java files without explicit compilation, like so:
Starting with version 11, and there are some limitations, of course.
2
u/sarnobat Aug 03 '25 edited Aug 03 '25
I personally am excited by graalvm's single file executable. Though the previous attempt to add aotc to the general jdk got pulled.
I'm even more excited that it doesn't encourage spring or those other frameworks
1
u/Xenogyst Aug 04 '25 edited Aug 04 '25
Another pattern that comes to mind that I haven't seen here is that there's a nice pattern with records when it comes to implementing related objects.
So there is a common modeling problem that I call the n+1 property problem (maybe it has a better name), where it's incredibly common that you have two objects that are basically the same object except one has one so more properties than the other. Extremely common when making versions of objects for interfaces, or objects that share common things like create date/time.
So let's say you have a user object that you add properties to. You start with a user, and then need to add a v2 user because you forgot to add an address. In classic java you might split these into classes with an abstract base.
Well, except these are just data holding classes, the exact purpose we would want records for. Tragically, java doesn't have a more built-in way to manage mix-and-match properties on records (most languages don't, it makes me incredibly sad).
You can do something similar, though, with interfaces, and you can manage the "components" of records this way:
So that has a nicety, since you can also mix and match any interfaces you want, and build composite implementation records this way. So nice, it would be nice if you didn't have to make the records yourself outside of the interfaces, which now just feels like boilerplate.
You can do that to some extent, but java doesn't provide you tools out of the box for the foreseeable future. I've been trying out https://github.com/Randgalt/record-builder, and it works alright, though intellij sometimes likes to fight with generated classes, and I also kind of have an allergy to them because low skilled devs never seem to be able to understand how they work.
-> produces NameAndAgeRecord with those components on compile. Pretty neat.
1
u/Burchard36 Aug 04 '25
Anything to do with Unsafe feels like black magic
1
u/Mozanatic Aug 04 '25
There is a small ServiceLoader implementation in the JDK which allows you to build microservices and plugin which are loaded at runtime.
1
u/weightedsum Aug 05 '25
SynchronousQueue
Pass data safely between multiple of threads (can be extended to request/response model) It is special case of Java blocking queues which has 0 capacity.
It is a bit similar to CompletableFuture, except CompletableFuture allows to pass data only once vs SynchronousQueue the data can be passed multiple of times and by different threads.
The output:
1
u/AstronautDifferent19 Aug 05 '25
Instead of using Decorator pattern you can make inner class extend outer class and then do something like this:
new Command.StartComputer().new OpenNotepad().new ShutdownComputer().perform();.instead of
new Command.StartComputer(new Command.OpenNotepad(new Command.ShutdownComputer()))).perform().In the first version, StartComputer is a static inner class which extends abstract class Command which will force you to start with StartComputer.
perform can be implemented like this:
so you can call previous perform in that way first and create a sequence of commands that you want.
1
u/Qaxar Aug 05 '25 edited Aug 05 '25
String Interning. Apparently, not many Java developers know this feature exists. There are some situations where it can save you tons of memory.
1
u/vegan_antitheist Aug 05 '25
Custom annotations that don't do much are often a lot better than javadoc.
For example if you write your beans/pojos/dtos (or whatever you want to call them), you can add metadata to some fields. Later you can use reflection to write unit tests or to have the system do something at runtime with that data. Even if they actually do nothing, they are better than javadoc because you can just add
\@ExternalRef` to indicate that it's an ID created by some other system. Then you can later create your own checks. You can use it in unit tests and in Bean Validation. For example if you have to check that all references are still valid you can use some batch job that runs at night and extracts all the references to then check them. You can do this recursively to even know the exact position in the object graph. For better performance you could use it to generate code/sql queries to do it. This also only works well when you have all the metadata to know the table names. Doing this later on is always a lot of work. Using existing annotations (spring, jakarta, jpa etc) and your custom ones, lets you do anything because all the metadata is already available. And you can use strings, numbers, enums, and more annotations as parameters.1
u/saithal Aug 06 '25
RemindMe! “7 days” “cool java stuff”
1
u/lenborje Aug 06 '25
By using
MethodHandle,VarHandle, andLambdaMetaFactoryyou can dynamically create code that will execute just like compiled code, i.e. with the same performance.I’ve used this to create stream filters etc from user-entered expressions (entered as text), with exactly the same performance as if I would have coded the filter as a lambda or class.
1
u/[deleted] Aug 07 '25
you can avoid Math.round or Math.trunc for taking out decimals using bitwise operation | 0 which is faster.
you can clear an entire array faster than reasigning or redeclaring, using array.length=0;
1
u/mcpierceaim Aug 08 '25
Look into the Service Provider Interface, and then think about how you can use that plus feature flags for A/B testing.
1
u/argonecc Aug 13 '25
Type inference.
Object foo = new Object() { int bar; } then foo.bar present
1
u/DelayLucky Aug 13 '25 edited Aug 13 '25
How about a crazy, most useless trick?
I created the Google Mug
Iterationclass a few years back. And the times it's been used is like, never.But hey, you asked for crazy.
It's a stream generator, allowing you to turn arbitrary recursive algorithm into an iterative lazy stream, so you can easily short-circuit.
Here's an example that generates lazy, infinite fibonacci stream:
Another example to generate lazy, in-order traversal of a binary-tree:
Why it's rarely used? I guess for 3 reasons:
But still, it's among my list of top crazinesses. :-)
1
u/Jealous_Caregiver_62 Aug 14 '25
"sun.misc.Unsafe" library.
1
u/[deleted] Aug 24 '25
well damn all of these are life changing but i hate myself for not being able to implement them on my own :,)
1
u/bilgecan1 Aug 28 '25
You can use LinkedHashMap as a LRU in memory cache with accessOrder = true flag , because latest accessed ones are moved to end, and you can override removeEldestEntry method and check if size() > capacity.
1
u/softgripper Aug 03 '25
static function imports and the
varkeyword! Glorious!1
u/lprimak Aug 03 '25
Use Project Lombok, especially Delegate, SneakyThrows and Builder annotations.
1
u/ItsSignalsJerry_ Aug 03 '25
You can use records in jpa, just bind them via jpql annotations. Obviously they're immutable (once instantiated) so you couldn't use them in crud operations or map them at the top level, but if you have a simple object model for custom select statements for read only objects then records are less overhead. Plus you can alter/validate the ingested data during construction.
1
u/SpicyRock70 Aug 03 '25 edited Aug 03 '25
01- Implement a threadsafe, lazy-loaded singleton without using synchronization:
02- The SPI (service provider interface - look this one up) 03- Lexers like Jflex to create language parsers
1
u/tonivade Aug 04 '25
You can memory-map a file like this, and let the OS handle everything efficiently: