GUICE
google sample:
http://www.ibm.com/developerworks/library/j-guice/
http://www.monperrus.net/martin/lecture-slides-dependency-injection-guice.pdf
http://ripper234.com/p/mapbinder-basics-in-guice/
https://github.com/google/guice/wiki/Multibindings
https://www.richardnichols.net/2010/08/session-replication-with-guice-java-web-applications/
http://www.iteye.com/topic/408661
http://stackoverflow.com/questions/16800810/get-the-implementation-type-for-an-interface-in-guice
advanced
http://www.lexicalscope.com/blog/2012/02/13/guava-eventbus-experiences/
https://github.com/google/guice/wiki/CustomInjections
more advanced
https://github.com/manzke/guice-automatic-injection
type literal
http://stackoverflow.com/questions/8655921/use-of-typeliteral-in-java
public class ListUser {
@Inject @Named("list") List<String> strings;
@Inject @Named("list") List<Integer> integers;
public String toString() {
return String.format("%s[strings=%s, integers=%s]",
getClass().getName(),
System.identityHashCode(strings),
System.identityHashCode(integers));
}
}
public class TypeLiteralModule extends AbstractModule {
protected void configure() {
bind(new TypeLiteral<List<String>>(){})
.annotatedWith(Names.named("list"))
.to(new TypeLiteral<ArrayList<String>>(){});
bind(new TypeLiteral<List<Integer>>(){})
.annotatedWith(Names.named("list"))
.to(new TypeLiteral<ArrayList<Integer>>(){});
}
}
or another approach
public class TypeLiteralModule extends AbstractModule {
protected void configure() {
bind(listOf(String.class))
.annotatedWith(Names.named("list"))
.to(arrayListOf(String.class));
bind(listOf(Integer.class))
.annotatedWith(Names.named("list"))
.to(arrayListOf(Integer.class));
}
@SuppressWarnings("unchecked")
static <T> TypeLiteral<List<T>> listOf(final Class<T> parameterType) {
return (TypeLiteral<List<T>>) TypeLiteral.get(new ParameterizedType() {
public Type[] getActualTypeArguments(){return new Type[]
{parameterType};}
public Type getRawType() { return List.class; }
public Type getOwnerType() { return null; }
});
}
@SuppressWarnings("unchecked")
static <T> TypeLiteral<ArrayList<T>> arrayListOf(final Class<T> parameterType) {
return (TypeLiteral<ArrayList<T>>) TypeLiteral.get(new ParameterizedType() {
public Type[] getActualTypeArguments(){return new Type[]
{parameterType};}
public Type getRawType() { return ArrayList.class; }
public Type getOwnerType() { return null; }
});
}
}
visitor:
http://stackoverflow.com/questions/16800810/get-the-implementation-type-for-an-interface-in-guice
https://github.com/google/guice/wiki/AssistedInject
extending
http://developer.vz.net/2012/02/08/extending-guice-2/
factory
override
https://publicobject.com/2008/05/overriding-bindings-in-guice.html
http://stackoverflow.com/questions/483087/overriding-binding-in-guice
create child injector
http://stackoverflow.com/questions/3078671/guice-injection-across-modules-for-sharing?rq=1
http://stackoverflow.com/questions/20307298/guice-injecting-an-object-from-an-installed-module-to-a-dependent-installed-mod?rq=1
https://github.com/google/guice/blob/master/core/test/com/google/inject/ParentInjectorTest.java
inject null
bind(KeyListener.class).toProvider(Providers.<KeyListener>of(null));
bind(Foo.class).toInstance(null);
single binding
http://www.mattinsler.com/post/26548600649/guicey-tips-google-guice-provider-modules
section 5.4 and section 7.1
Each thread has a boolean prop-erty that represents its interrupted status; interrupting a thread sets this status.
Interruption is a cooperative mechanism. One thread cannot force another to
stop what it is doing and do something else; when thread A interrupts thread B, A
is merely requesting that B stop what it is doing when it gets to a convenient stopping
point—if it feels like it.
If a thread is interrupted when it is not blocked, its interrupted status is set,
and it is up to the activity being cancelled to poll the interrupted status to detect
interruption. In this way interruption is “sticky”—if it doesn’t trigger an InterruptedException,
evidence of interruption persists until someone deliberately
clears the interrupted status.
When a method can throw InterruptedException, it is telling you that it is a blocking method.
When your code calls a method that throws InterruptedException, then your
method is a blocking method too, and must have a plan for responding to interruption.
For library code, there are basically two choices, either throw InterruptedException or restore the interrupted status
by calling interrupt again:
- Propagate the InterruptedException. This is often the most sensible policy if
you can get away with it—just propagate the InterruptedException to your
caller. This could involve not catching InterruptedException, or catching it
and throwing it again after performing some brief activity-specific cleanup.
- Restore the interrupt. Sometimes you cannot throw InterruptedException, for
instance when your code is part of a Runnable. In these situations, you must
catch InterruptedException and restore the interrupted status by calling
interrupt on the current thread, so that code higher up the call stack can
see that an interrupt was issued, as demonstrated in Listing 5.10.
You can get much more sophisticated with interruption, but these two approaches
should work in the vast majority of situations. But there is one thing
you should not do with InterruptedException—catch it and do nothing in response.
This deprives code higher up on the call stack of the opportunity to act on
the interruption, because the evidence that the thread was interrupted is lost.
The only situation in which it is acceptable to swallow an interrupt is when you are extending
Thread and therefore control all the code higher up on the call stack.
class PrimeProducer extends Thread {
private final BlockingQueue<BigInteger> queue;
PrimeProducer(BlockingQueue<BigInteger> queue) {
this.queue = queue;
}
public void run() {
try {
BigInteger p = BigInteger.ONE;
while (!Thread.currentThread().isInterrupted())
queue.put(p = p.nextProbablePrime());
} catch (InterruptedException consumed) {
/* Allow thread to exit */
}
}
public void cancel() { interrupt(); }
}
PrimeProducer swallows the interrupt, but does so with the knowledge that the
thread is about to terminate and that therefore there is no code higher up on the
call stack that needs to know about the interruption. Most code does not know
what thread it will run in and so should preserve the interrupted status.
It is important to distinguish between how tasks and threads should react to interruption.
Tasks do not execute in threads they own; they borrow threads owned by a
service such as a thread pool. This is why most blocking library methods simply throw InterruptedException
in response to an interrupt. just communicate the interruption back to the caller so that code higher up on
the call stack can take further action.
A task needn’t necessarily drop everything when it detects an interruption
request—it can choose to postpone it until a more opportune time by remembering
that it was interrupted, finishing the task it was performing, and then throwing
InterruptedException or otherwise indicating interruption. This technique
can protect data structures from corruption when an activity is interrupted in the
middle of an update.
Whether a task interprets interruption as cancellation
or takes some other action on interruption, it should take care to preserve
the executing thread’s interruption status. If it is not simply going to propagate
InterruptedException to its caller, it should restore the interruption status after
catching InterruptedException:
Thread.currentThread().interrupt();
Activities that do not support cancellation but still call interruptible blocking
methods will have to call them in a loop, retrying when interruption is detected.
In this case, they should save the interruption status locally and restore it just
before returning, as shown in Listing 7.7, rather than immediately upon catching
InterruptedException. Setting the interrupted status too early could result in an
infinite loop, because most interruptible blocking methods check the interrupted
status on entry and throw InterruptedException immediately if it is set.
public Task getNextTask(BlockingQueue<Task> queue) {
boolean interrupted = false;
try {
while (true) {
try {
return queue.take();
} catch (InterruptedException e) {
interrupted = true;
// fall through and retry
}
}
} finally {
if (interrupted)
Thread.currentThread().interrupt();
}
}
Listing 7.7. Noncancelable task that restores interruption before exit.
Blocking library methods like Thread.sleep and Object.wait try to detect
when a thread has been interrupted and return early. They respond to interruption
by clearing the interrupted status and throwing InterruptedException,
indicating that the blocking operation completed early due to interruption
The interrupt
method interrupts the target thread, and isInterrupted returns the interrupted
status of the target thread. The poorly named static interrupted method
clears the interrupted status of the current thread and returns its previous value;
this is the only way to clear the interrupted status.
public class Thread {
public void interrupt() { … }
public boolean isInterrupted() { … }
public static boolean interrupted() { … }
…
}
Dealing with non-interruptible blocking
Many blocking library methods respond to interruption by returning early and
throwing InterruptedException, which makes it easier to build tasks that are
responsive to cancellation. However, not all blocking methods or blocking mechanisms
are responsive to interruption; if a thread is blocked performing synchronous
socket I/O or waiting to acquire an intrinsic lock, interruption has no
effect other than setting the thread’s interrupted status. We can sometimes convince
threads blocked in noninterruptible activities to stop by means similar to
interruption, but this requires greater awareness of why the thread is blocked.
148 Chapter 7. Cancellation and Shutdown
Synchronous socket I/O in java.io. The common form of blocking I/O in
server applications is reading or writing to a socket. Unfortunately, the
read and write methods in InputStream and OutputStream are not responsive
to interruption, but closing the underlying socket makes any
threads blocked in read or write throw a SocketException.
Synchronous I/O in java.nio. Interrupting a thread waiting on an InterruptibleChannel
causes it to throw ClosedByInterruptException and close the
channel (and also causes all other threads blocked on the channel to throw
ClosedByInterruptException). Closing an InterruptibleChannel causes
threads blocked on channel operations to throw AsynchronousCloseException.
Most standard Channels implement InterruptibleChannel.
Asynchronous I/O with Selector. If a thread is blocked in Selector.select (in
java.nio.channels), calling close or wakeup causes it to return prematurely.
Lock acquisition. If a thread is blocked waiting for an intrinsic lock, there is
nothing you can do to stop it short of ensuring that it eventually acquires
the lock and makes enough progress that you can get its attention some
other way. However, the explicit Lock classes offer the lockInterruptibly
method, which allows you to wait for a lock and still be responsive to
interrupts—see Chapter 13.
ReaderThread in Listing 7.11 shows
ReaderThread
encapsulates cancellation of socket-using threads by overriding interrupt;
the same can be done for tasks by overriding Future.cancel.
public class ReaderThread extends Thread {
private final Socket socket;
private final InputStream in;
public ReaderThread(Socket socket) throws IOException {
this.socket = socket;
this.in = socket.getInputStream();
}
public void interrupt() {
try {
socket.close();
}
catch (IOException ignored) { }
finally {
super.interrupt();
}
}
public void run() {
try {
byte[] buf = new byte[BUFSZ];
while (true) {
int count = in.read(buf);
if (count < 0)
break;
else if (count > 0)
processBuffer(buf, count);
}
} catch (IOException e) { /* Allow thread to exit */ }
}
}