+8
@@ -0,0 +1,8 @@
|
||||
package com.baeldung.annotations;
|
||||
|
||||
import javax.annotation.Generated;
|
||||
|
||||
@RetentionAnnotation
|
||||
@Generated("Available only on source code")
|
||||
public class AnnotatedClass {
|
||||
}
|
||||
+12
@@ -0,0 +1,12 @@
|
||||
package com.baeldung.annotations;
|
||||
|
||||
import java.lang.annotation.Retention;
|
||||
import java.lang.annotation.RetentionPolicy;
|
||||
import java.lang.annotation.Target;
|
||||
|
||||
import static java.lang.annotation.ElementType.TYPE;
|
||||
|
||||
@Target(TYPE)
|
||||
@Retention(RetentionPolicy.RUNTIME)
|
||||
public @interface RetentionAnnotation {
|
||||
}
|
||||
+18
@@ -0,0 +1,18 @@
|
||||
package com.baeldung.annotations;
|
||||
|
||||
import org.junit.Test;
|
||||
|
||||
import java.lang.annotation.Annotation;
|
||||
|
||||
import static org.hamcrest.core.Is.is;
|
||||
import static org.junit.Assert.assertThat;
|
||||
|
||||
public class AnnotatedClassUnitTest {
|
||||
|
||||
@Test
|
||||
public void whenAnnotationRetentionPolicyRuntime_shouldAccess() {
|
||||
AnnotatedClass anAnnotatedClass = new AnnotatedClass();
|
||||
Annotation[] annotations = anAnnotatedClass.getClass().getAnnotations();
|
||||
assertThat(annotations.length, is(1));
|
||||
}
|
||||
}
|
||||
@@ -25,7 +25,7 @@
|
||||
</dependencies>
|
||||
|
||||
<properties>
|
||||
<assertj.version>3.18.0</assertj.version>
|
||||
<assertj.version>3.19.0</assertj.version>
|
||||
</properties>
|
||||
|
||||
</project>
|
||||
|
||||
+91
@@ -0,0 +1,91 @@
|
||||
package com.baeldung.collections.dequestack;
|
||||
|
||||
import java.util.ArrayDeque;
|
||||
import java.util.Collection;
|
||||
import java.util.Deque;
|
||||
import java.util.Iterator;
|
||||
|
||||
public class ArrayLifoStack<E> implements LifoStack<E> {
|
||||
private final Deque<E> deque = new ArrayDeque<>();
|
||||
|
||||
@Override
|
||||
public void push(E item) {
|
||||
deque.addFirst(item);
|
||||
}
|
||||
|
||||
@Override
|
||||
public E pop() {
|
||||
return deque.removeFirst();
|
||||
}
|
||||
|
||||
@Override
|
||||
public E peek() {
|
||||
return deque.peekFirst();
|
||||
}
|
||||
|
||||
// implementing methods from the Collection interface
|
||||
@Override
|
||||
public int size() {
|
||||
return deque.size();
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean isEmpty() {
|
||||
return deque.isEmpty();
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean contains(Object o) {
|
||||
return deque.contains(o);
|
||||
}
|
||||
|
||||
@Override
|
||||
public Iterator<E> iterator() {
|
||||
return deque.iterator();
|
||||
}
|
||||
|
||||
@Override
|
||||
public Object[] toArray() {
|
||||
return deque.toArray();
|
||||
}
|
||||
|
||||
@Override
|
||||
public <T> T[] toArray(T[] a) {
|
||||
return deque.toArray(a);
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean add(E e) {
|
||||
return deque.add(e);
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean remove(Object o) {
|
||||
return deque.remove(o);
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean containsAll(Collection<?> c) {
|
||||
return deque.containsAll(c);
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean addAll(Collection<? extends E> c) {
|
||||
return deque.addAll(c);
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean removeAll(Collection<?> c) {
|
||||
return deque.removeAll(c);
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean retainAll(Collection<?> c) {
|
||||
return deque.retainAll(c);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void clear() {
|
||||
deque.clear();
|
||||
}
|
||||
}
|
||||
+12
@@ -0,0 +1,12 @@
|
||||
package com.baeldung.collections.dequestack;
|
||||
|
||||
import java.util.Collection;
|
||||
|
||||
public interface LifoStack<E> extends Collection<E> {
|
||||
|
||||
E peek();
|
||||
|
||||
E pop();
|
||||
|
||||
void push(E item);
|
||||
}
|
||||
+90
@@ -0,0 +1,90 @@
|
||||
package com.baeldung.collections.dequestack;
|
||||
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import java.util.ArrayDeque;
|
||||
import java.util.Deque;
|
||||
import java.util.Iterator;
|
||||
import java.util.Stack;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
|
||||
class StackVsDequeUnitTest {
|
||||
|
||||
@Test
|
||||
void givenAStack_whenAccessByIndex_thenElementCanBeRead() {
|
||||
Stack<String> myStack = new Stack<>();
|
||||
myStack.push("I am the 1st element."); //index 0
|
||||
myStack.push("I am the 2nd element."); //index 1
|
||||
myStack.push("I am the 3rd element."); //index 2
|
||||
//access by index
|
||||
assertThat(myStack.get(0)).isEqualTo("I am the 1st element.");
|
||||
}
|
||||
|
||||
@Test
|
||||
void givenAStack_whenIterate_thenFromBottomToTop() {
|
||||
Stack<String> myStack = new Stack<>();
|
||||
myStack.push("I am at the bottom.");
|
||||
myStack.push("I am in the middle.");
|
||||
myStack.push("I am at the top.");
|
||||
|
||||
Iterator<String> it = myStack.iterator();
|
||||
|
||||
assertThat(it).toIterable().containsExactly(
|
||||
"I am at the bottom.",
|
||||
"I am in the middle.",
|
||||
"I am at the top.");
|
||||
}
|
||||
|
||||
@Test
|
||||
void givenAStack_whenAddOrRemoveByIndex_thenElementCanBeAddedOrRemoved() {
|
||||
Stack<String> myStack = new Stack<>();
|
||||
myStack.push("I am the 1st element.");
|
||||
myStack.push("I am the 3rd element.");
|
||||
|
||||
assertThat(myStack.size()).isEqualTo(2);
|
||||
|
||||
//insert by index
|
||||
myStack.add(1, "I am the 2nd element.");
|
||||
assertThat(myStack.size()).isEqualTo(3);
|
||||
assertThat(myStack.get(1)).isEqualTo("I am the 2nd element.");
|
||||
//remove by index
|
||||
myStack.remove(1);
|
||||
assertThat(myStack.size()).isEqualTo(2);
|
||||
}
|
||||
|
||||
@Test
|
||||
void givenADeque_whenAddOrRemoveLastElement_thenTheLastElementCanBeAddedOrRemoved() {
|
||||
Deque<String> myStack = new ArrayDeque<>();
|
||||
myStack.push("I am the 1st element.");
|
||||
myStack.push("I am the 2nd element.");
|
||||
myStack.push("I am the 3rd element.");
|
||||
|
||||
assertThat(myStack.size()).isEqualTo(3);
|
||||
|
||||
//insert element to the bottom of the stack
|
||||
myStack.addLast("I am the NEW element.");
|
||||
assertThat(myStack.size()).isEqualTo(4);
|
||||
assertThat(myStack.peek()).isEqualTo("I am the 3rd element.");
|
||||
|
||||
//remove element from the bottom of the stack
|
||||
String removedStr = myStack.removeLast();
|
||||
assertThat(myStack.size()).isEqualTo(3);
|
||||
assertThat(removedStr).isEqualTo("I am the NEW element.");
|
||||
}
|
||||
|
||||
@Test
|
||||
void givenADeque_whenIterate_thenFromTopToBottom() {
|
||||
Deque<String> myStack = new ArrayDeque<>();
|
||||
myStack.push("I am at the bottom.");
|
||||
myStack.push("I am in the middle.");
|
||||
myStack.push("I am at the top.");
|
||||
|
||||
Iterator<String> it = myStack.iterator();
|
||||
|
||||
assertThat(it).toIterable().containsExactly(
|
||||
"I am at the top.",
|
||||
"I am in the middle.",
|
||||
"I am at the bottom.");
|
||||
}
|
||||
}
|
||||
@@ -7,4 +7,5 @@ This module contains articles about Map data structures in Java.
|
||||
- [Comparing Two HashMaps in Java](https://www.baeldung.com/java-compare-hashmaps)
|
||||
- [The Map.computeIfAbsent() Method](https://www.baeldung.com/java-map-computeifabsent)
|
||||
- [Collections.synchronizedMap vs. ConcurrentHashMap](https://www.baeldung.com/java-synchronizedmap-vs-concurrenthashmap)
|
||||
- [Java HashMap Load Factor](https://www.baeldung.com/java-hashmap-load-factor)
|
||||
- More articles: [[<-- prev]](/core-java-modules/core-java-collections-maps-2)
|
||||
|
||||
@@ -17,7 +17,7 @@
|
||||
<dependencies>
|
||||
<dependency>
|
||||
<groupId>com.baeldung.servicemodule</groupId>
|
||||
<artifactId>servicemodule</artifactId>
|
||||
<artifactId>servicemodule2</artifactId>
|
||||
<version>${servicemodule.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
@@ -41,4 +41,4 @@
|
||||
<providermodule.version>1.0</providermodule.version>
|
||||
</properties>
|
||||
|
||||
</project>
|
||||
</project>
|
||||
|
||||
@@ -8,3 +8,4 @@ This module contains articles about generics in Java
|
||||
- [Raw Types in Java](https://www.baeldung.com/raw-types-java)
|
||||
- [Super Type Tokens in Java Generics](https://www.baeldung.com/java-super-type-tokens)
|
||||
- [Java Warning “unchecked conversion”](https://www.baeldung.com/java-unchecked-conversion)
|
||||
- [Java Warning “Unchecked Cast”](https://www.baeldung.com/java-warning-unchecked-cast)
|
||||
|
||||
+26
@@ -0,0 +1,26 @@
|
||||
package com.baeldung.uncheckedcast;
|
||||
|
||||
import java.time.LocalDate;
|
||||
import java.time.Month;
|
||||
import java.util.Date;
|
||||
import java.util.HashMap;
|
||||
import java.util.Map;
|
||||
|
||||
public class UncheckedCast {
|
||||
public static Map getRawMap() {
|
||||
Map rawMap = new HashMap();
|
||||
rawMap.put("date 1", LocalDate.of(2021, Month.FEBRUARY, 10));
|
||||
rawMap.put("date 2", LocalDate.of(1992, Month.AUGUST, 8));
|
||||
rawMap.put("date 3", LocalDate.of(1976, Month.NOVEMBER, 18));
|
||||
return rawMap;
|
||||
}
|
||||
|
||||
public static Map getRawMapWithMixedTypes() {
|
||||
Map rawMap = new HashMap();
|
||||
rawMap.put("date 1", LocalDate.of(2021, Month.FEBRUARY, 10));
|
||||
rawMap.put("date 2", LocalDate.of(1992, Month.AUGUST, 8));
|
||||
rawMap.put("date 3", LocalDate.of(1976, Month.NOVEMBER, 18));
|
||||
rawMap.put("date 4", new Date());
|
||||
return rawMap;
|
||||
}
|
||||
}
|
||||
+25
@@ -0,0 +1,25 @@
|
||||
package com.baeldung.uncheckedcast;
|
||||
|
||||
import org.junit.Assert;
|
||||
import org.junit.Test;
|
||||
|
||||
import java.time.LocalDate;
|
||||
import java.time.Month;
|
||||
import java.util.Map;
|
||||
|
||||
public class UncheckedCastUnitTest {
|
||||
|
||||
@Test
|
||||
public void givenRawMap_whenCastToTypedMap_shouldHaveCompilerWarning() {
|
||||
Map<String, LocalDate> castFromRawMap = (Map<String, LocalDate>) UncheckedCast.getRawMap();
|
||||
Assert.assertEquals(3, castFromRawMap.size());
|
||||
Assert.assertEquals(castFromRawMap.get("date 2"), LocalDate.of(1992, Month.AUGUST, 8));
|
||||
}
|
||||
|
||||
@Test(expected = ClassCastException.class)
|
||||
public void givenMixTypedRawMap_whenCastToTypedMap_shouldThrowClassCastException() {
|
||||
Map<String, LocalDate> castFromRawMap = (Map<String, LocalDate>) UncheckedCast.getRawMapWithMixedTypes();
|
||||
Assert.assertEquals(4, castFromRawMap.size());
|
||||
Assert.assertTrue(castFromRawMap.get("date 4").isAfter(castFromRawMap.get("date 3")));
|
||||
}
|
||||
}
|
||||
@@ -14,5 +14,12 @@
|
||||
<version>0.0.1-SNAPSHOT</version>
|
||||
<relativePath>../</relativePath>
|
||||
</parent>
|
||||
|
||||
<dependencies>
|
||||
<dependency>
|
||||
<groupId>org.assertj</groupId>
|
||||
<artifactId>assertj-core</artifactId>
|
||||
<version>3.6.1</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
</project>
|
||||
+64
@@ -0,0 +1,64 @@
|
||||
package com.baeldung.selector;
|
||||
|
||||
import org.junit.Test;
|
||||
import java.io.IOException;
|
||||
import java.nio.channels.Pipe;
|
||||
import java.nio.channels.SelectableChannel;
|
||||
import java.nio.channels.Selector;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Collections;
|
||||
import java.util.List;
|
||||
import java.util.concurrent.CountDownLatch;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
|
||||
import static java.nio.channels.SelectionKey.OP_READ;
|
||||
|
||||
public class SelectorManualTest {
|
||||
|
||||
@Test
|
||||
public void whenWakeUpCalledOnSelector_thenBlockedThreadReturns() throws IOException, InterruptedException {
|
||||
Pipe pipe = Pipe.open();
|
||||
|
||||
Selector selector = Selector.open();
|
||||
SelectableChannel channel = pipe.source();
|
||||
channel.configureBlocking(false);
|
||||
channel.register(selector, OP_READ);
|
||||
|
||||
List<String> invocationStepsTracker = Collections.synchronizedList(new ArrayList<>());
|
||||
|
||||
CountDownLatch latch = new CountDownLatch(1);
|
||||
|
||||
Thread thread = new Thread(() -> {
|
||||
invocationStepsTracker.add(">> Count down");
|
||||
latch.countDown();
|
||||
try {
|
||||
invocationStepsTracker.add(">> Start select");
|
||||
selector.select();
|
||||
invocationStepsTracker.add(">> End select");
|
||||
} catch (IOException e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
});
|
||||
|
||||
invocationStepsTracker.add(">> Start await");
|
||||
thread.start();
|
||||
latch.await();
|
||||
invocationStepsTracker.add(">> End await");
|
||||
|
||||
invocationStepsTracker.add(">> Wakeup thread");
|
||||
|
||||
selector.wakeup();
|
||||
channel.close();
|
||||
|
||||
assertThat(invocationStepsTracker)
|
||||
.containsExactly(
|
||||
">> Start await",
|
||||
">> Count down",
|
||||
">> Start select",
|
||||
">> End await",
|
||||
">> Wakeup thread",
|
||||
">> End select"
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -3,3 +3,4 @@
|
||||
- [Introduction to Docker Compose](https://www.baeldung.com/docker-compose)
|
||||
- [Reusing Docker Layers with Spring Boot](https://www.baeldung.com/docker-layers-spring-boot)
|
||||
- [Running Spring Boot with PostgreSQL in Docker Compose](https://www.baeldung.com/spring-boot-postgresql-docker)
|
||||
- [How To Configure Java Heap Size Inside a Docker Container](https://www.baeldung.com/ops/docker-jvm-heap-size)
|
||||
|
||||
@@ -0,0 +1,4 @@
|
||||
FROM openjdk:8u92-jdk-alpine
|
||||
COPY /src /src/
|
||||
RUN mkdir /app && ls /src && javac /src/main/java/com/baeldung/docker/heapsizing/PrintXmxXms.java -d /app
|
||||
CMD java -version && java $JAVA_OPTS -cp /app com.baeldung.docker.heapsizing.PrintXmxXms
|
||||
@@ -0,0 +1,61 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
|
||||
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
|
||||
<modelVersion>4.0.0</modelVersion>
|
||||
<parent>
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-starter-parent</artifactId>
|
||||
<version>2.4.2</version>
|
||||
<relativePath/> <!-- lookup parent from repository -->
|
||||
</parent>
|
||||
<groupId>com.baeldung.docker</groupId>
|
||||
<artifactId>heap-sizing</artifactId>
|
||||
<version>0.0.1-SNAPSHOT</version>
|
||||
<name>heap-sizing</name>
|
||||
<description>Demo project for Spring Boot</description>
|
||||
<properties>
|
||||
<java.version>11</java.version>
|
||||
</properties>
|
||||
<dependencies>
|
||||
<dependency>
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-starter-webflux</artifactId>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-starter-test</artifactId>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>io.projectreactor</groupId>
|
||||
<artifactId>reactor-test</artifactId>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
|
||||
<build>
|
||||
<plugins>
|
||||
<plugin>
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-maven-plugin</artifactId>
|
||||
<configuration>
|
||||
<image>
|
||||
<name>heapsizing-demo</name>
|
||||
</image>
|
||||
</configuration>
|
||||
</plugin>
|
||||
<plugin>
|
||||
<groupId>com.google.cloud.tools</groupId>
|
||||
<artifactId>jib-maven-plugin</artifactId>
|
||||
<version>2.7.1</version>
|
||||
|
||||
<configuration>
|
||||
<to>
|
||||
<image>heapsizing-demo-jib</image>
|
||||
</to>
|
||||
</configuration>
|
||||
</plugin>
|
||||
</plugins>
|
||||
</build>
|
||||
|
||||
</project>
|
||||
+19
@@ -0,0 +1,19 @@
|
||||
package com.baeldung.docker.heapsizing;
|
||||
|
||||
import org.springframework.boot.SpringApplication;
|
||||
import org.springframework.boot.autoconfigure.SpringBootApplication;
|
||||
|
||||
import java.util.logging.Logger;
|
||||
|
||||
import static com.baeldung.docker.heapsizing.PrintXmxXms.logMemory;
|
||||
|
||||
@SpringBootApplication
|
||||
public class HeapSizingApplication {
|
||||
private static final Logger logger = Logger.getLogger(HeapSizingApplication.class.getName());
|
||||
|
||||
public static void main(String[] args) {
|
||||
SpringApplication.run(HeapSizingApplication.class, args);
|
||||
logMemory(logger);
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,36 @@
|
||||
package com.baeldung.docker.heapsizing;
|
||||
|
||||
import java.lang.management.ManagementFactory;
|
||||
import java.lang.management.MemoryMXBean;
|
||||
import java.lang.management.MemoryPoolMXBean;
|
||||
import java.util.logging.Level;
|
||||
import java.util.logging.Logger;
|
||||
|
||||
public class PrintXmxXms {
|
||||
|
||||
private static final Logger logger = Logger.getLogger(PrintXmxXms.class.getName());
|
||||
|
||||
public static void main(String[] args) {
|
||||
logMemory(logger);
|
||||
}
|
||||
|
||||
/**
|
||||
* We're reusing this method in HeapSizingApplication, therefore this method was extracted
|
||||
* to avoid repetition.
|
||||
*/
|
||||
static void logMemory(Logger logger) {
|
||||
float mb = 1024f * 1024f;
|
||||
MemoryMXBean memoryBean = ManagementFactory.getMemoryMXBean();
|
||||
|
||||
// xmx controls the maximum size of the memory allocation pool,
|
||||
// which includes the heap, the garbage collector's survivor space, and other pools.
|
||||
float xmx = memoryBean.getHeapMemoryUsage().getMax() / mb;
|
||||
float xms = memoryBean.getHeapMemoryUsage().getInit() / mb;
|
||||
logger.log(Level.INFO, "Initial Memory (xms) : {0}mb", xms);
|
||||
logger.log(Level.INFO, "Max Memory (xmx) : {0}mb", xmx);
|
||||
|
||||
for (MemoryPoolMXBean mp : ManagementFactory.getMemoryPoolMXBeans()) {
|
||||
logger.log(Level.INFO, "Pool: {0} (type {1}) = {2}", new Object[]{ mp.getName(), mp.getType(), mp.getUsage().getMax() / mb });
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,6 @@
|
||||
package com.baeldung.map.hashing;
|
||||
|
||||
class Member {
|
||||
Integer id;
|
||||
String name;
|
||||
}
|
||||
+8
@@ -0,0 +1,8 @@
|
||||
package com.baeldung.map.hashing;
|
||||
|
||||
public class MemberWithBadHashing extends Member {
|
||||
@Override
|
||||
public int hashCode() {
|
||||
return name.hashCode();
|
||||
}
|
||||
}
|
||||
+18
@@ -0,0 +1,18 @@
|
||||
package com.baeldung.map.hashing;
|
||||
|
||||
import com.google.common.base.Charsets;
|
||||
import com.google.common.hash.HashFunction;
|
||||
import com.google.common.hash.Hashing;
|
||||
|
||||
public class MemberWithGuavaHashing extends Member {
|
||||
@Override
|
||||
public int hashCode() {
|
||||
HashFunction hashFunction = Hashing.murmur3_32();
|
||||
return hashFunction.newHasher()
|
||||
.putInt(id)
|
||||
.putString(name, Charsets.UTF_8)
|
||||
.hash().hashCode();
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
@@ -0,0 +1,18 @@
|
||||
package com.baeldung.map.hashing;
|
||||
|
||||
public class MemberWithId extends Member {
|
||||
@Override
|
||||
public boolean equals(Object o) {
|
||||
if (this == o) return true;
|
||||
if (o == null || getClass() != o.getClass()) return false;
|
||||
|
||||
MemberWithId that = (MemberWithId) o;
|
||||
|
||||
return id.equals(that.id);
|
||||
}
|
||||
|
||||
@Override
|
||||
public int hashCode() {
|
||||
return id;
|
||||
}
|
||||
}
|
||||
+23
@@ -0,0 +1,23 @@
|
||||
package com.baeldung.map.hashing;
|
||||
|
||||
import java.util.Objects;
|
||||
|
||||
public class MemberWithIdAndName extends Member {
|
||||
public static final int PRIME = 31;
|
||||
|
||||
@Override
|
||||
public boolean equals(Object o) {
|
||||
if (this == o) return true;
|
||||
if (o == null || getClass() != o.getClass()) return false;
|
||||
MemberWithObjects that = (MemberWithObjects) o;
|
||||
return Objects.equals(id, that.id) &&
|
||||
Objects.equals(name, that.name);
|
||||
}
|
||||
|
||||
@Override
|
||||
public int hashCode() {
|
||||
int result = id.hashCode();
|
||||
result = PRIME * result + (name == null ? 0 : name.hashCode());
|
||||
return result;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,19 @@
|
||||
package com.baeldung.map.hashing;
|
||||
|
||||
import java.util.Objects;
|
||||
|
||||
public class MemberWithObjects extends Member {
|
||||
@Override
|
||||
public boolean equals(Object o) {
|
||||
if (this == o) return true;
|
||||
if (o == null || getClass() != o.getClass()) return false;
|
||||
MemberWithObjects that = (MemberWithObjects) o;
|
||||
return Objects.equals(id, that.id) &&
|
||||
Objects.equals(name, that.name);
|
||||
}
|
||||
|
||||
@Override
|
||||
public int hashCode() {
|
||||
return Objects.hash(id, name);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,76 @@
|
||||
package com.baeldung.map.hashing;
|
||||
|
||||
import com.google.common.base.Stopwatch;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import java.time.Duration;
|
||||
import java.util.HashMap;
|
||||
import java.util.SplittableRandom;
|
||||
import java.util.function.Supplier;
|
||||
|
||||
public class HashingUnitTest {
|
||||
|
||||
public static final int SAMPLES = 1000000;
|
||||
private SplittableRandom random = new SplittableRandom();
|
||||
|
||||
private String[] names = {"John", "Adam", "Suzie"};
|
||||
|
||||
@Test
|
||||
void givenPrimitiveByteArrayKey_whenRetrievingFromMap_shouldRetrieveDifferentObjects() {
|
||||
// bad hashing example is prohibitively slow for bigger samples
|
||||
// Duration[] badHashing = testDuration(MemberWithBadHashing::new);
|
||||
Duration[] withId = testDuration(MemberWithId::new);
|
||||
Duration[] withObjects = testDuration(MemberWithObjects::new);
|
||||
Duration[] withIdAndName = testDuration(MemberWithIdAndName::new);
|
||||
|
||||
// System.out.println("Inserting with bad hashing:");
|
||||
// System.out.println(badHashing[0]);
|
||||
// System.out.println("Getting with bad hashing:");
|
||||
// System.out.println(badHashing[1]);
|
||||
|
||||
System.out.println("Inserting with id hashing:");
|
||||
System.out.println(withId[0]);
|
||||
System.out.println("Getting with id hashing:");
|
||||
System.out.println(withId[1]);
|
||||
|
||||
System.out.println("Inserting with id and name hashing:");
|
||||
System.out.println(withIdAndName[0]);
|
||||
System.out.println("Getting with id and name hashing:");
|
||||
System.out.println(withIdAndName[1]);
|
||||
|
||||
System.out.println("Inserting with Objects hashing:");
|
||||
System.out.println(withObjects[0]);
|
||||
System.out.println("Getting with Objects hashing:");
|
||||
System.out.println(withObjects[1]);
|
||||
}
|
||||
|
||||
private String randomName() {
|
||||
return names[random.nextInt(2)];
|
||||
}
|
||||
|
||||
private <T extends Member> Duration[] testDuration(Supplier<T> factory) {
|
||||
HashMap<T, String> map = new HashMap<>();
|
||||
Stopwatch stopwatch = Stopwatch.createUnstarted();
|
||||
|
||||
stopwatch.start();
|
||||
for(int i = 0; i < SAMPLES; i++) {
|
||||
T member = factory.get();
|
||||
member.id = i;
|
||||
member.name = randomName();
|
||||
map.put(member, member.name);
|
||||
}
|
||||
stopwatch.stop();
|
||||
Duration elapsedInserting = stopwatch.elapsed();
|
||||
stopwatch.reset();
|
||||
|
||||
stopwatch.start();
|
||||
for (T key : map.keySet()) {
|
||||
map.get(key);
|
||||
}
|
||||
stopwatch.stop();
|
||||
Duration elapsedGetting = stopwatch.elapsed();
|
||||
stopwatch.reset();
|
||||
|
||||
return new Duration[]{elapsedInserting, elapsedGetting};
|
||||
}
|
||||
}
|
||||
+9
-1
@@ -7,7 +7,7 @@ It contains the code of a simple API for some CRUD operations built using Spring
|
||||
|
||||
- Maven
|
||||
- JDK 8
|
||||
- MongoDB
|
||||
- MongoDB (Note: for the Write Extracted Data to a File Using JMeter example MongoDB is not required)
|
||||
|
||||
### Running
|
||||
|
||||
@@ -36,6 +36,14 @@ Or create a new one via a POST:
|
||||
$ curl -X POST -H "Content-Type:application/json" -d '{ "firstName" : "Dassi", "lastName" : "Orleando", "phoneNumber": "+237 545454545", "email": "[email protected]" }' localhost:8080/students
|
||||
```
|
||||
|
||||
### Available UUID API
|
||||
|
||||
You can view the test response using curl:
|
||||
|
||||
```bash
|
||||
$ curl localhost:8080/api/uuid
|
||||
```
|
||||
|
||||
Now with default configurations it will be available at: [http://localhost:8080](http://localhost:8080)
|
||||
|
||||
Enjoy it :)
|
||||
|
||||
@@ -0,0 +1,18 @@
|
||||
package com.baeldung.controller;
|
||||
|
||||
import com.baeldung.model.Response;
|
||||
import org.springframework.web.bind.annotation.GetMapping;
|
||||
import org.springframework.web.bind.annotation.RestController;
|
||||
|
||||
import java.util.UUID;
|
||||
|
||||
import static java.lang.String.format;
|
||||
|
||||
@RestController
|
||||
public class RetrieveUuidController {
|
||||
|
||||
@GetMapping("/api/uuid")
|
||||
public Response uuid() {
|
||||
return new Response(format("Test message... %s.", UUID.randomUUID()));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,40 @@
|
||||
package com.baeldung.model;
|
||||
|
||||
import java.time.Instant;
|
||||
import java.util.UUID;
|
||||
|
||||
public class Response {
|
||||
private Instant timestamp;
|
||||
private UUID uuid;
|
||||
private String message;
|
||||
|
||||
public Response(String message) {
|
||||
this.timestamp = Instant.now();
|
||||
this.uuid = UUID.randomUUID();
|
||||
this.message = message;
|
||||
}
|
||||
|
||||
public Instant getTimestamp() {
|
||||
return timestamp;
|
||||
}
|
||||
|
||||
public void setTimestamp(Instant timestamp) {
|
||||
this.timestamp = timestamp;
|
||||
}
|
||||
|
||||
public UUID getUuid() {
|
||||
return uuid;
|
||||
}
|
||||
|
||||
public void setUuid(UUID uuid) {
|
||||
this.uuid = uuid;
|
||||
}
|
||||
|
||||
public String getMessage() {
|
||||
return message;
|
||||
}
|
||||
|
||||
public void setMessage(String message) {
|
||||
this.message = message;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,124 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<jmeterTestPlan version="1.2" properties="5.0" jmeter="5.4.1">
|
||||
<hashTree>
|
||||
<TestPlan guiclass="TestPlanGui" testclass="TestPlan" testname="Test Plan" enabled="true">
|
||||
<stringProp name="TestPlan.comments">To run this test plan you must also be running the Spring application "JmeterApplication" That can be found in this directory</stringProp>
|
||||
<boolProp name="TestPlan.functional_mode">false</boolProp>
|
||||
<boolProp name="TestPlan.tearDown_on_shutdown">true</boolProp>
|
||||
<boolProp name="TestPlan.serialize_threadgroups">false</boolProp>
|
||||
<elementProp name="TestPlan.user_defined_variables" elementType="Arguments" guiclass="ArgumentsPanel" testclass="Arguments" testname="User Defined Variables" enabled="true">
|
||||
<collectionProp name="Arguments.arguments"/>
|
||||
</elementProp>
|
||||
<stringProp name="TestPlan.user_define_classpath"></stringProp>
|
||||
</TestPlan>
|
||||
<hashTree>
|
||||
<ThreadGroup guiclass="ThreadGroupGui" testclass="ThreadGroup" testname="Thread Group" enabled="true">
|
||||
<stringProp name="ThreadGroup.on_sample_error">continue</stringProp>
|
||||
<elementProp name="ThreadGroup.main_controller" elementType="LoopController" guiclass="LoopControlPanel" testclass="LoopController" testname="Loop Controller" enabled="true">
|
||||
<boolProp name="LoopController.continue_forever">false</boolProp>
|
||||
<stringProp name="LoopController.loops">1</stringProp>
|
||||
</elementProp>
|
||||
<stringProp name="ThreadGroup.num_threads">1</stringProp>
|
||||
<stringProp name="ThreadGroup.ramp_time">1</stringProp>
|
||||
<boolProp name="ThreadGroup.scheduler">false</boolProp>
|
||||
<stringProp name="ThreadGroup.duration"></stringProp>
|
||||
<stringProp name="ThreadGroup.delay"></stringProp>
|
||||
<boolProp name="ThreadGroup.same_user_on_next_iteration">true</boolProp>
|
||||
</ThreadGroup>
|
||||
<hashTree>
|
||||
<HTTPSamplerProxy guiclass="HttpTestSampleGui" testclass="HTTPSamplerProxy" testname="Call GET Test endpoint " enabled="true">
|
||||
<elementProp name="HTTPsampler.Arguments" elementType="Arguments" guiclass="HTTPArgumentsPanel" testclass="Arguments" testname="User Defined Variables" enabled="true">
|
||||
<collectionProp name="Arguments.arguments"/>
|
||||
</elementProp>
|
||||
<stringProp name="HTTPSampler.domain">localhost</stringProp>
|
||||
<stringProp name="HTTPSampler.port">8080</stringProp>
|
||||
<stringProp name="HTTPSampler.protocol">http</stringProp>
|
||||
<stringProp name="HTTPSampler.contentEncoding"></stringProp>
|
||||
<stringProp name="HTTPSampler.path">/api/test</stringProp>
|
||||
<stringProp name="HTTPSampler.method">GET</stringProp>
|
||||
<boolProp name="HTTPSampler.follow_redirects">true</boolProp>
|
||||
<boolProp name="HTTPSampler.auto_redirects">false</boolProp>
|
||||
<boolProp name="HTTPSampler.use_keepalive">true</boolProp>
|
||||
<boolProp name="HTTPSampler.DO_MULTIPART_POST">false</boolProp>
|
||||
<stringProp name="HTTPSampler.embedded_url_re"></stringProp>
|
||||
<stringProp name="HTTPSampler.connect_timeout"></stringProp>
|
||||
<stringProp name="HTTPSampler.response_timeout"></stringProp>
|
||||
</HTTPSamplerProxy>
|
||||
<hashTree>
|
||||
<JSONPostProcessor guiclass="JSONPostProcessorGui" testclass="JSONPostProcessor" testname="JSON Extractor" enabled="true">
|
||||
<stringProp name="JSONPostProcessor.referenceNames">message</stringProp>
|
||||
<stringProp name="JSONPostProcessor.jsonPathExprs">$.message</stringProp>
|
||||
<stringProp name="JSONPostProcessor.match_numbers">1</stringProp>
|
||||
<boolProp name="JSONPostProcessor.compute_concat">true</boolProp>
|
||||
<stringProp name="JSONPostProcessor.defaultValues">NOT_FOUND</stringProp>
|
||||
</JSONPostProcessor>
|
||||
<hashTree/>
|
||||
<BeanShellPostProcessor guiclass="TestBeanGUI" testclass="BeanShellPostProcessor" testname="Response to file using BeanShell PostProcessor" enabled="true">
|
||||
<stringProp name="filename"></stringProp>
|
||||
<stringProp name="parameters"></stringProp>
|
||||
<boolProp name="resetInterpreter">false</boolProp>
|
||||
<stringProp name="script">FileWriter fWriter = new FileWriter("<path>/result.txt", true);
|
||||
BufferedWriter buff = new BufferedWriter(fWriter);
|
||||
|
||||
buff.write("Response Code : " + ctx.getPreviousResult().getResponseCode());
|
||||
buff.write(System.getProperty("line.separator"));
|
||||
buff.write("Response Headers : " + ctx.getPreviousResult().getResponseHeaders());
|
||||
buff.write(System.getProperty("line.separator"));
|
||||
buff.write("Response Body : " + new String(ctx.getPreviousResult().getResponseData()));
|
||||
|
||||
buff.write("More complex extraction : " + vars.get("message"));
|
||||
|
||||
buff.close();
|
||||
fWriter.close();</stringProp>
|
||||
</BeanShellPostProcessor>
|
||||
<hashTree/>
|
||||
<ResultSaver guiclass="ResultSaverGui" testclass="ResultSaver" testname="Response to file using file write Listener" enabled="true">
|
||||
<stringProp name="FileSaver.filename">response</stringProp>
|
||||
<boolProp name="FileSaver.errorsonly">false</boolProp>
|
||||
<boolProp name="FileSaver.successonly">false</boolProp>
|
||||
<boolProp name="FileSaver.skipsuffix">false</boolProp>
|
||||
<boolProp name="FileSaver.skipautonumber">false</boolProp>
|
||||
</ResultSaver>
|
||||
<hashTree/>
|
||||
</hashTree>
|
||||
<ResultCollector guiclass="ViewResultsFullVisualizer" testclass="ResultCollector" testname="View Results Tree" enabled="true">
|
||||
<boolProp name="ResultCollector.error_logging">false</boolProp>
|
||||
<objProp>
|
||||
<name>saveConfig</name>
|
||||
<value class="SampleSaveConfiguration">
|
||||
<time>true</time>
|
||||
<latency>true</latency>
|
||||
<timestamp>true</timestamp>
|
||||
<success>true</success>
|
||||
<label>true</label>
|
||||
<code>true</code>
|
||||
<message>true</message>
|
||||
<threadName>true</threadName>
|
||||
<dataType>true</dataType>
|
||||
<encoding>false</encoding>
|
||||
<assertions>true</assertions>
|
||||
<subresults>true</subresults>
|
||||
<responseData>false</responseData>
|
||||
<samplerData>false</samplerData>
|
||||
<xml>false</xml>
|
||||
<fieldNames>true</fieldNames>
|
||||
<responseHeaders>false</responseHeaders>
|
||||
<requestHeaders>false</requestHeaders>
|
||||
<responseDataOnError>false</responseDataOnError>
|
||||
<saveAssertionResultsFailureMessage>true</saveAssertionResultsFailureMessage>
|
||||
<assertionsResultsToSave>0</assertionsResultsToSave>
|
||||
<bytes>true</bytes>
|
||||
<sentBytes>true</sentBytes>
|
||||
<url>true</url>
|
||||
<threadCounts>true</threadCounts>
|
||||
<idleTime>true</idleTime>
|
||||
<connectTime>true</connectTime>
|
||||
</value>
|
||||
</objProp>
|
||||
<stringProp name="filename"></stringProp>
|
||||
</ResultCollector>
|
||||
<hashTree/>
|
||||
</hashTree>
|
||||
</hashTree>
|
||||
</hashTree>
|
||||
</jmeterTestPlan>
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user