### Question:
PerThreadDocumentBuilderProvider implements DocumentBuilderProvider { public DocumentBuilder getDocumentBuilder(final boolean validating) throws ParserConfigurationException { return validating ? validatingDBCache.getInstanceForCurrentThread() : nonValidatingDBCache.getInstanceForCurrentThread(); } PerThreadDocumentBuilderProvider(final DocumentBuilderProvider delegate, final int maxSize);   PerThreadDocumentBuilderProvider(final DocumentBuilderProvider delegate); DocumentBuilder getDocumentBuilder(final boolean validating);  }### Answer:
@Test public void shouldReturnSameInstanceForSameThread() throws ParserConfigurationException { boolean validating = false; DocumentBuilder builder1 = testProvider.getDocumentBuilder(validating); DocumentBuilder builder2 = testProvider.getDocumentBuilder(validating); assertThat(builder1).isSameAs(builder2); }
@Test public void shouldReturnDifferentInstancesForDifferentThreads() throws Exception { boolean validating = false; ExecutorService otherThread = Executors.newSingleThreadExecutor(); DocumentBuilder builder1 = testProvider.getDocumentBuilder(validating); DocumentBuilder builder2 = otherThread.submit(getDocBuilderAction(validating)).get(); assertThat(builder1).isNotSameAs(builder2); }
@Test public void shouldEvictLeastRecentlyAccessedElements() throws Exception { int maxSize = 1; boolean validating = false; ExecutorService otherThread = Executors.newSingleThreadExecutor(); testProvider = new PerThreadDocumentBuilderProvider(new MockDocumentBuilderProvider(), maxSize); DocumentBuilder builder1 = testProvider.getDocumentBuilder(validating); otherThread.submit(getDocBuilderAction(validating)).get(); DocumentBuilder builder2 = testProvider.getDocumentBuilder(validating); assertThat(builder1).isNotSameAs(builder2); }
@Test public void shouldCacheValidatingAndNonValidatingInstancesSeparately() throws Exception { DocumentBuilder validatingBuilder = testProvider.getDocumentBuilder(true); DocumentBuilder nonValidatingBuilder = testProvider.getDocumentBuilder(false); assertThat(validatingBuilder).isNotSameAs(nonValidatingBuilder); }