r/ProgrammerTIL • u/_guy_fawkes • Mar 09 '18
Java [Java] TIL recursive imports are allowed
In the java source, java.util.Arrays imports java.util.concurrent.ForkJoinPool. ForkJoinPool, in turn, imports java.util.Arrays.
Another example:
% tree
.
└── com
└── example
└── src
├── test
│ ├── Test.class
│ └── Test.java
└── tmp
├── Tmp.class
└── Tmp.java
% cat com/example/src/test/Test.java
package com.example.src.test;
import com.example.src.tmp.Tmp;
public class Test {}
% cat com/example/src/tmp/Tmp.java
package com.example.src.tmp;
import com.example.src.test.Test;
public class Tmp {}
29
Upvotes
View all comments
Show parent comment
3
u/kilogram007 Mar 10 '18
Suppose, in a multithreaded program, two threads call getFoo at the same time. Each thread sees that there's no Foo, and creates one. They each get a Foo, but only one Foo is stored; the other is discarded, and all changes made to it lost.
In a library, or when making this code multithreaded, this kind of bug could be very hard to find, so it's good practice to protect it with a lock. But affects single-threaded performance. A trade-off that didn't have to be made with a better organization of classes s.t. there are no loops.