How is Java’s ThreadLocal implemented under the hood?

All of the answers here are correct, but a little disappointing as they somewhat gloss over how clever ThreadLocal‘s implementation is. I was just looking at the source code for ThreadLocal and was pleasantly impressed by how it’s implemented. The Naive Implementation If I asked you to implement a ThreadLocal<T> class given the API described … Read more

Setting user agent of a java URLConnection

Just for clarification: setRequestProperty(“User-Agent”, “Mozilla …”) now works just fine and doesn’t append java/xx at the end! At least with Java 1.6.30 and newer. I listened on my machine with netcat(a port listener): $ nc -l -p 8080 It simply listens on the port, so you see anything which gets requested, like raw http-headers. And … Read more

Programmatically configure LogBack appender

Here a simple example that works for me (note that I use the FileAppender in this example) import org.slf4j.LoggerFactory; import ch.qos.logback.classic.Level; import ch.qos.logback.classic.Logger; import ch.qos.logback.classic.LoggerContext; import ch.qos.logback.classic.encoder.PatternLayoutEncoder; import ch.qos.logback.classic.spi.ILoggingEvent; import ch.qos.logback.core.FileAppender; public class Loggerutils { public static void main(String[] args) { Logger foo = createLoggerFor(“foo”, “foo.log”); Logger bar = createLoggerFor(“bar”, “bar.log”); foo.info(“test”); bar.info(“bar”); } private … Read more

Why java.security.NoSuchProviderException No such provider: BC?

Im not very familiar with the Android sdk, but it seems that the android-sdk comes with the BouncyCastle provider already added to the security. What you will have to do in the PC environment is just add it manually, Security.addProvider(new org.bouncycastle.jce.provider.BouncyCastleProvider()); if you have access to the policy file, just add an entry like: security.provider.5=org.bouncycastle.jce.provider.BouncyCastleProvider … Read more

Before and After Suite execution hook in jUnit 4.x

Yes, it is possible to reliably run set up and tear down methods before and after any tests in a test suite. Let me demonstrate in code: package com.test; import org.junit.AfterClass; import org.junit.BeforeClass; import org.junit.runner.RunWith; import org.junit.runners.Suite; import org.junit.runners.Suite.SuiteClasses; @RunWith(Suite.class) @SuiteClasses({Test1.class, Test2.class}) public class TestSuite { @BeforeClass public static void setUp() { System.out.println(“setting up”); } … Read more

Counting method invocations in Unit tests

It sounds like you may want to be using the .expects(1) type methods that mock frameworks usually provide. Using mockito, if you were testing a List and wanted to verify that clear was called 3 times and add was called at least once with these parameters you do the following: List mock = mock(List.class); someCodeThatInteractsWithMock(); … Read more