Skip to content

Commit 532a048

Browse files
committed
Thread Safety + More
1. Removed Mockito because it wasn't used. 2. Normalized formatting across files. 3. Normalized the use of `final` across files. 4. Improve thread safety in `EmbeddedPostgres` by making `lockChannel` and `lock` final instead of volatile. 5. Switched from `MD5` to `SHA-512` in `EmbeddedPostgres` for the digest.
1 parent 9343e48 commit 532a048

29 files changed

Lines changed: 399 additions & 548 deletions

build.gradle.kts

Lines changed: 0 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -19,7 +19,6 @@ val commonsCompressVersion = providers.gradleProperty("commons_compress_version"
1919
val flywayVersion = providers.gradleProperty("flyway_version")
2020
val junitVersion = providers.gradleProperty("junit_version")
2121
val liquibaseVersion = providers.gradleProperty("liquibase_version")
22-
val mockitoVersion = providers.gradleProperty("mockito_version")
2322
val postgresqlVersion = providers.gradleProperty("postgresql_version")
2423
val slf4jVersion = providers.gradleProperty("slf4j_version")
2524
val xzVersion = providers.gradleProperty("xz_version")
@@ -33,7 +32,6 @@ version = projectVersion.get()
3332

3433
repositories { mavenCentral() }
3534

36-
val mockitoAgent by configurations.creating
3735
dependencies {
3836
dokkaPlugin("org.jetbrains.dokka:kotlin-as-java-plugin:${dokkaVersion.get()}")
3937

@@ -55,9 +53,6 @@ dependencies {
5553
testImplementation("org.liquibase:liquibase-core:${liquibaseVersion.get()}")
5654
testImplementation(platform("org.junit:junit-bom:${junitVersion.get()}"))
5755
testImplementation("org.junit.jupiter:junit-jupiter")
58-
testImplementation("org.mockito:mockito-core:${mockitoVersion.get()}")
59-
60-
mockitoAgent("org.mockito:mockito-core:${mockitoVersion.get()}") { isTransitive = false }
6156

6257
testRuntimeOnly("org.junit.platform:junit-platform-launcher")
6358
testRuntimeOnly("org.slf4j:slf4j-simple:${slf4jVersion.get()}")
@@ -69,12 +64,6 @@ java {
6964
withSourcesJar()
7065
withJavadocJar()
7166
}
72-
abstract class MockitoAgentArgs @Inject constructor(objects: ObjectFactory) : CommandLineArgumentProvider {
73-
@get:InputFiles
74-
@get:PathSensitive(PathSensitivity.RELATIVE)
75-
val agentFiles: ConfigurableFileCollection = objects.fileCollection()
76-
override fun asArguments(): Iterable<String> = agentFiles.files.map { "-javaagent:${it.absolutePath}" }
77-
}
7867
tasks {
7968
withType<JavaCompile>().configureEach {
8069
options.encoding = "UTF-8"
@@ -85,8 +74,6 @@ tasks {
8574
withType<JavaExec>().configureEach { defaultCharacterEncoding = "UTF-8" }
8675
withType<Javadoc>().configureEach { options.encoding = "UTF-8" }
8776
withType<Test>().configureEach {
88-
val provider = objects.newInstance(MockitoAgentArgs::class.java).apply { agentFiles.from(mockitoAgent) }
89-
jvmArgumentProviders.add(provider)
9077
defaultCharacterEncoding = "UTF-8"
9178
useJUnitPlatform()
9279
}

gradle.properties

Lines changed: 0 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -23,8 +23,6 @@ flyway_version = 11.16.0
2323
junit_version = 6.0.1
2424
# Check this on https://central.sonatype.com/artifact/org.liquibase/liquibase-core/
2525
liquibase_version = 5.0.1
26-
# Check this on https://central.sonatype.com/artifact/org.mockito/mockito-core/
27-
mockito_version = 5.20.0
2826
# Check this on https://central.sonatype.com/artifact/org.postgresql/postgresql/
2927
postgresql_version = 42.7.8
3028
# Check this on https://central.sonatype.com/artifact/org.slf4j/slf4j-api/

src/main/java/com/smushytaco/postgres/embedded/ConnectionInfo.java

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -35,7 +35,6 @@
3535
* @param properties additional connection properties (maybe empty)
3636
*/
3737
public record ConnectionInfo(String dbName, int port, String user, Map<String, String> properties) {
38-
3938
/**
4039
* Creates a {@link ConnectionInfo} without any additional connection properties.
4140
*

src/main/java/com/smushytaco/postgres/embedded/DatabaseConnectionPreparer.java

Lines changed: 3 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -29,10 +29,9 @@
2929
* at the {@link javax.sql.DataSource} level.
3030
*/
3131
public interface DatabaseConnectionPreparer extends DatabasePreparer {
32-
3332
@Override
34-
default void prepare(DataSource ds) throws SQLException {
35-
try (Connection c = ds.getConnection()) {
33+
default void prepare(final DataSource ds) throws SQLException {
34+
try (final Connection c = ds.getConnection()) {
3635
prepare(c);
3736
}
3837
}
@@ -47,5 +46,5 @@ default void prepare(DataSource ds) throws SQLException {
4746
* @param conn an active JDBC connection to the target database
4847
* @throws SQLException if an error occurs while preparing the database
4948
*/
50-
void prepare(Connection conn) throws SQLException;
49+
void prepare(final Connection conn) throws SQLException;
5150
}

src/main/java/com/smushytaco/postgres/embedded/DatabasePreparer.java

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -41,5 +41,5 @@ public interface DatabasePreparer {
4141
* @param ds the {@link DataSource} representing the target database
4242
* @throws SQLException if a database access error occurs during preparation
4343
*/
44-
void prepare(DataSource ds) throws SQLException;
44+
void prepare(final DataSource ds) throws SQLException;
4545
}

src/main/java/com/smushytaco/postgres/embedded/DefaultPostgresBinaryResolver.java

Lines changed: 16 additions & 25 deletions
Original file line numberDiff line numberDiff line change
@@ -42,7 +42,6 @@
4242
* It also includes fallback behavior for unsupported or emulated architectures.
4343
*/
4444
public class DefaultPostgresBinaryResolver implements PgBinaryResolver {
45-
4645
private static final Logger logger = LoggerFactory.getLogger(DefaultPostgresBinaryResolver.class);
4746

4847
/**
@@ -56,15 +55,14 @@ public class DefaultPostgresBinaryResolver implements PgBinaryResolver {
5655
private DefaultPostgresBinaryResolver() {}
5756

5857
@Override
59-
public InputStream getPgBinary(String system, String machineHardware) throws IOException {
60-
String architecture = ArchUtils.normalize(machineHardware);
61-
String distribution = LinuxUtils.getDistributionName();
58+
public InputStream getPgBinary(final String system, final String machineHardware) throws IOException {
59+
final String architecture = ArchUtils.normalize(machineHardware);
60+
final String distribution = LinuxUtils.getDistributionName();
6261

63-
if (logger.isInfoEnabled())
64-
logger.info("Detected distribution: '{}'", Optional.ofNullable(distribution).orElse("Unknown"));
62+
if (logger.isInfoEnabled()) logger.info("Detected distribution: '{}'", Optional.ofNullable(distribution).orElse("Unknown"));
6563

6664
if (distribution != null) {
67-
Resource resource = findPgBinary(normalize(format("postgres-%s-%s-%s.txz", system, architecture, distribution)));
65+
final Resource resource = findPgBinary(normalize(format("postgres-%s-%s-%s.txz", system, architecture, distribution)));
6866
if (resource != null) {
6967
logger.info("Distribution specific postgres binaries found: '{}'", resource.getFilename());
7068
return resource.getInputStream();
@@ -97,45 +95,38 @@ public InputStream getPgBinary(String system, String machineHardware) throws IOE
9795
throw new IllegalStateException("Missing embedded postgres binaries");
9896
}
9997

100-
private static Resource findPgBinary(String resourceLocation) throws IOException {
98+
private static Resource findPgBinary(final String resourceLocation) throws IOException {
10199
logger.trace("Searching for postgres binaries - location: '{}'", resourceLocation);
102-
ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
103-
List<URL> urls = Collections.list(classLoader.getResources(resourceLocation));
100+
final ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
101+
final List<URL> urls = Collections.list(classLoader.getResources(resourceLocation));
104102

105103
if (urls.size() > 1) {
106104
logger.error("Detected multiple binaries of the same architecture: '{}'", urls);
107105
throw new IllegalStateException("Duplicate embedded postgres binaries");
108106
}
109-
if (urls.size() == 1) {
110-
return new Resource(urls.getFirst());
111-
}
107+
if (urls.size() == 1) return new Resource(urls.getFirst());
112108

113109
return null;
114110
}
115111

116-
private static String normalize(String input) {
117-
if (input == null || input.isBlank()) {
118-
return input;
119-
}
112+
private static String normalize(final String input) {
113+
if (input == null || input.isBlank()) return input;
120114
return input.replace(' ', '_').toLowerCase(Locale.ROOT);
121115
}
122116

123117
private record Resource(URL url) {
124-
125118
public String getFilename() {
126-
String path = URLDecoder.decode(url.getPath(), StandardCharsets.UTF_8);
127-
int slash = path.lastIndexOf('/');
119+
final String path = URLDecoder.decode(url.getPath(), StandardCharsets.UTF_8);
120+
final int slash = path.lastIndexOf('/');
128121
return (slash != -1) ? path.substring(slash + 1) : path;
129122
}
130123

131124
public InputStream getInputStream() throws IOException {
132-
URLConnection con = this.url.openConnection();
125+
final URLConnection con = this.url.openConnection();
133126
try {
134127
return con.getInputStream();
135-
} catch (IOException ex) {
136-
if (con instanceof HttpURLConnection httpURLConnection) {
137-
httpURLConnection.disconnect();
138-
}
128+
} catch (final IOException ex) {
129+
if (con instanceof final HttpURLConnection httpURLConnection) httpURLConnection.disconnect();
139130
throw ex;
140131
}
141132
}

0 commit comments

Comments
 (0)