Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Improve GsonTest.testGetAdapter_Concurrency #2177

Merged
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
29 changes: 16 additions & 13 deletions gson/src/test/java/com/google/gson/GsonTest.java
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,7 @@
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicReference;
import junit.framework.TestCase;

Expand Down Expand Up @@ -102,6 +103,17 @@ public void testGetAdapter_Null() {
}

public void testGetAdapter_Concurrency() {
class DummyAdapter<T> extends TypeAdapter<T> {
@Override public void write(JsonWriter out, T value) throws IOException {
throw new AssertionError("not needed for test");
}

@Override public T read(JsonReader in) throws IOException {
throw new AssertionError("not needed for test");
}
}

final AtomicInteger adapterInstancesCreated = new AtomicInteger(0);
final AtomicReference<TypeAdapter<?>> threadAdapter = new AtomicReference<>();
final Class<?> requestedType = Number.class;

Expand Down Expand Up @@ -130,24 +142,15 @@ public void testGetAdapter_Concurrency() {
}

// Create a new dummy adapter instance

@SuppressWarnings("unchecked")
TypeAdapter<T> r = (TypeAdapter<T>) new TypeAdapter<Number>() {
@Override public void write(JsonWriter out, Number value) throws IOException {
throw new AssertionError("not needed for test");
}

@Override public Number read(JsonReader in) throws IOException {
throw new AssertionError("not needed for test");
}
};
return r;
adapterInstancesCreated.incrementAndGet();
return new DummyAdapter<>();
}
})
.create();

TypeAdapter<?> adapter = gson.getAdapter(requestedType);
assertNotNull(adapter);
assertTrue(adapter instanceof DummyAdapter);
assertEquals(2, adapterInstancesCreated.get());
// Should be the same adapter instance the concurrent thread received
assertSame(threadAdapter.get(), adapter);
}
Expand Down