Skip to content

Instantly share code, notes, and snippets.

@yongboy
Created May 21, 2012 07:39
Show Gist options
  • Save yongboy/2760990 to your computer and use it in GitHub Desktop.
Save yongboy/2760990 to your computer and use it in GitHub Desktop.
QueueFactory.java
public final class QueueFactory {
private static final boolean useUnsafe = DetectionUtil.hasUnsafe();
private static final InternalLogger LOGGER = InternalLoggerFactory.getInstance(QueueFactory.class);
private QueueFactory() {
// only use static methods!
}
/**
* Create a new unbound {@link BlockingQueue}
*
* @param itemClass the {@link Class} type which will be used as {@link BlockingQueue} items
* @return queue the {@link BlockingQueue} implementation
*/
public static <T> BlockingQueue<T> createQueue(Class<T> itemClass) {
// if we run in java >=7 its the best to just use the LinkedTransferQueue which
// comes with java bundled. See #273
if (DetectionUtil.javaVersion() >= 6) {
return new jsr166y.LinkedTransferQueue<T>();
}
try {
if (useUnsafe) {
return new LinkedTransferQueue<T>();
}
} catch (Throwable t) {
// For whatever reason an exception was thrown while loading the LinkedTransferQueue
//
// This mostly happens because of a custom classloader or security policy that did not allow us to access the
// com.sun.Unmisc class. So just log it and fallback to the old LegacyLinkedTransferQueue that works in all cases
if (LOGGER.isDebugEnabled()) {
LOGGER.debug("Unable to instance LinkedTransferQueue, fallback to LegacyLinkedTransferQueue", t);
}
}
return new LegacyLinkedTransferQueue<T>();
}
/**
* Create a new unbound {@link BlockingQueue}
*
* @param collection the collection which should get copied to the newly created {@link BlockingQueue}
* @param itemClass the {@link Class} type which will be used as {@link BlockingQueue} items
* @return queue the {@link BlockingQueue} implementation
*/
public static <T> BlockingQueue<T> createQueue(Collection<? extends T> collection, Class<T> itemClass) {
// if we run in java >=7 its the best to just use the LinkedTransferQueue which
// comes with java bundled. See #273
if (DetectionUtil.javaVersion() >= 6) {
return new jsr166y.LinkedTransferQueue<T>();
}
try {
if (useUnsafe) {
return new LinkedTransferQueue<T>(collection);
}
} catch (Throwable t) {
// For whatever reason an exception was thrown while loading the LinkedTransferQueue
//
// This mostly happens because of a custom classloader or security policy that did not allow us to access the
// com.sun.Unmisc class. So just log it and fallback to the old LegacyLinkedTransferQueue that works in all cases
if (LOGGER.isDebugEnabled()) {
LOGGER.debug("Unable to instance LinkedTransferQueue, fallback to LegacyLinkedTransferQueue", t);
}
}
return new LegacyLinkedTransferQueue<T>(collection);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment