Friday, January 31, 2014

Learn from Paul's stuff

Learn from Paul's stuff:

snap cubes, popsicle sticks
PA day
Please meet your child's teacher outside the kindergarten doors at entry and dismissal times.
Receive a late slip.
Snowflakes tumble to the ground.
Giggle giggle as it snows.
Grab your sled and go, go, go!
And the snowman's carrot rose...
Nobble, nibble, CRUNCH.

Tuesday, January 28, 2014

Three kinds implementation for Fibonacci

import java.math.BigInteger;

public class Fib {

public static void main(String[] args) throws Exception {
printFib1(10);
System.out.println();
printFib2(10);
System.out.println();
printFib3(10);
}

public static void printFib1(int n){
        int f = 0;
        int g = 1;
        for(int i = 1; i <= n; i++)
        {
        System.out.print(f + " ");
            f = f + g;
            g = f - g;
        }
}

public static void printFib2(int n){
for(int i=1;i<=n;i++){
System.out.print(fib2(i)+" ");
}
}

private static long fib2(int n){
if(n<=2)
return n-1;
else
return fib2(n-1)+fib2(n-2);
}

public static void printFib3(int n){
BigInteger[] result = getFib(n);
for(BigInteger num:result){
System.out.print(num+" ");
}
}

private static BigInteger[] getFib(int number){
BigInteger[] result = new BigInteger[0];
if(number>0){
result = new BigInteger[number];
if(number==1){
result[0] = BigInteger.valueOf(0);
}
else if(number==2){
result[0] = BigInteger.valueOf(0);
result[1] = BigInteger.valueOf(1);
}
else{
result[0] = BigInteger.valueOf(0);
result[1] = BigInteger.valueOf(1);
for(int i=2;i<number;i++){
result[i] = result[i-1].add(result[i-2]);
}
}
}
return result;
}

}

Monday, January 27, 2014

Data structures and algorithms in Java (Robert Lafore)

A data structure is an arrangement of data in a computer’s
memory (or sometimes on a disk). Data structures include
arrays, linked lists, stacks, binary trees, and hash tables,
among others. Algorithmsmanipulate the data in these
structures in various ways, such as searching for a particular data item and sorting the data.

TODO Arrays

Logback and SLF4jJ(another)

Logback default level is DEBUG:
TRACE < DEBUG < INFO <  WARN < ERROR.
Below requires: slf4j-api-1.7.5.jar, logback-core-1.0.13.jar and logback-classic-1.0.13.jar
Except code that configures logback (if such code exists) client code does not need to depend on logback.
Logger logger = LoggerFactory.getLogger("chapters.introduction.HelloWorld1");
logger.debug("Hello world.");
LoggerContext lc = (LoggerContext) LoggerFactory.getILoggerFactory();
StatusPrinter.print(lc);
Calling the LoggerFactory.getLogger method with the same name will always return a reference to the exact same logger object.
Thus, it is possible to configure a logger and then to retrieve the same instance somewhere else in the code without passing around references.
appenders are inherited additively from the logger hierarchy. For example, if a console appender is added to the root logger, then all
enabled logging requests will at least print on the console.

A two argument variant is also available. For example, you can write:
logger.debug("The new entry is {}. It replaces {}.", entry, oldEntry);
If three or more arguments need to be passed, an Object[] variant is also available. For example, you can write:
Object[] paramArray = {newVal, below, above};
logger.debug("Value {} was inserted between {} and {}.", paramArray);

the initialization steps that logback follows to try to configure itself:
1. Logback tries to find a file called logback.groovy in the classpath.
2. If no such file is found, logback tries to find a file called logback-test.xml in the classpath.
3. If no such file is found, it checks for the file logback.xml in the classpath..
4. If neither file is found, logback configures itself automatically using the BasicConfigurator which will cause logging output to be directed to the console.
existing log4j users can convert their log4j.properties files to logback.xml using our PropertiesTranslator web-application
Here is a configuration file equivalent to the one established by BasicConfigurator:
<configuration>
  <appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
    <!-- encoders are assigned the type
         ch.qos.logback.classic.encoder.PatternLayoutEncoder by default -->
    <encoder>
      <pattern>%d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n</pattern>
    </encoder>
  </appender>
  <root level="debug">
    <appender-ref ref="STDOUT" />
  </root>
</configuration>

You may specify the location of the default configuration file with a system property named "logback.configurationFile".
The value of this property can be a URL, a resource on the class path or a path to a file external to the application.
java -Dlogback.configurationFile=/path/to/config.xml chapters.configuration.MyApp1
Note that the file extension must be ".xml" or ".groovy". Other extensions are ignored.

If instructed to do so, logback-classic will scan for changes in its configuration file and automatically
reconfigure itself when the configuration file changes.
<configuration scan="true">
  ...
</configuration>
By default, the configuration file will be scanned for changes once every minute.
<configuration scan="true" scanPeriod="30 seconds" >
  ...
</configuration>

The below example, the appender named FILE is attached to the chapters.configuration.Foo logger.
Moreover, the chapters.configuration.Foo logger has its additivity flag set to false such that its logging
output will be sent to the appender named FILE but not to any appender attached higher in the hierarchy.
<configuration>
  <appender name="FILE" class="ch.qos.logback.core.FileAppender">
    <file>foo.log</file>
    <encoder>
      <pattern>%date %level [%thread] %logger{10} [%file : %line] %msg%n</pattern>
    </encoder>
  </appender>

  <appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
    <encoder>
      <pattern>%msg%n</pattern>
    </encoder>
  </appender>

  <logger name="chapters.configuration.Foo" additivity="false">
    <appender-ref ref="FILE" />
  </logger>

  <root level="debug">
    <appender-ref ref="STDOUT" />
  </root>
</configuration>

The SMTPAppender relies on the JavaMail API. It has been tested with JavaMail API version 1.4.
By default, the outgoing message will contain the last 256 messages seen by SMTPAppender. If
your heart so desires, you may set a different buffer size as shown in the next example.
<configuration>  
  <appender name="EMAIL" class="ch.qos.logback.classic.net.SMTPAppender">
    <smtpHost>smtp.gmail.com</smtpHost>
    <smtpPort>465</smtpPort>
    <SSL>true</SSL>
    <username>YOUR_USERNAME@gmail.com</username>
    <password>YOUR_GMAIL_PASSWORD</password>
    <to>${to}</to>
    <from>${from}</from>
    <subject>%logger{20} - %m</subject>
    <layout class="ch.qos.logback.classic.html.HTMLLayout"/>

    <cyclicBufferTracker class="ch.qos.logback.core.spi.CyclicBufferTracker">
      <!-- send just one log entry per email -->
      <bufferSize>1</bufferSize>
    </cyclicBufferTracker>
  </appender>

  <root level="DEBUG">
    <appender-ref ref="EMAIL" />
  </root>
</configuration>

Wednesday, January 22, 2014

Java Concurrency in Practice



They share process-wide resources such as memory and file handles, but each thread has its own program counter, stack, and local variables.
multiple threads within the same program can be scheduled simultaneously on multiple CPUs.
But without explicit synchronization to coordinate access to shared data, a thread may modify variables that another thread
is in the middle of using, with unpredictable results.
Threads are useful in GUI applications for improving the responsiveness of the user interface, and in server applications
for improving resource utilization and throughput.
GUI applications are inherently asynchronous. Swing and AWT address this problem by creating a separate thread for handling user-initiated
events and updating the graphical view presented to the user. Swing programs achieve their thread safety by confining all access to
GUI components to the event thread. If an application wants to manipulate the GUI from outside the event thread, it must cause the code
that will manipulate the GUI to run in the event thread instead.

If multiple threads access the same mutable state variable without appropriate synchronization, your program is broken. There are three ways to fix it:
Don't share the state variable across threads;
Make the state variable immutable; or
Use synchronization whenever accessing the state variable.
It is far easier to design a class to be thread-safe than to retrofit it for thread safety later.
concurrency bugs are so difficult to reproduce and debug, the benefit of a small performance gain on some infrequently used code path may
well be dwarfed by the risk that the program will fail in the field.
a class is thread-safe when it continues to behave correctly when accessed from multiple threads.
Stateless objects are always thread-safe.
A race condition occurs when getting the right answer relies on lucky timing. (count++, meet friends at Starbucks, Lazy Initialization)
To ensure thread safety, check-then-act operations (like lazy initialization) and read-modify-write operations (like increment) must always be atomic.

@ThreadSafe
public class CountingFactorizer implements Servlet {
    private final AtomicLong count = new AtomicLong(0);

    public long getCount() { return count.get(); }

    public void service(ServletRequest req, ServletResponse resp) {
        BigInteger i = extractFromRequest(req);
        BigInteger[] factors = factor(i);
        count.incrementAndGet();
        encodeIntoResponse(resp, factors);
    }
}

Where practical, use existing thread-safe objects, like AtomicLong, to manage your class's state. this makes it easier to maintain and verify thread safety.

A synchronized block has two parts: a reference to an object that will serve as the lock, and a block of code to be guarded by that lock.
A synchronized method is a shorthand for a synchronized block that spans an entire method body, and whose lock is the object on which
the method is being invoked. (Static synchronized methods use the Class object for the lock.)
intrinsic locks are reentrant, if a thread tries to acquire a lock that it already holds, the request succeeds.
Reentrancy is implemented by associating with each lock an acquisition count and an owning thread.
if synchronization is used to coordinate access to a variable, it is needed everywhere that variable is accessed. Further,
when using locks to coordinate access to a variable, the same lock must be used wherever that variable is accessed.
Code auditing tools like FindBugs can identify when a variable is frequently but not always accessed with a lock held, which may indicate a bug.

Avoid holding locks during lengthy computations or operations at risk of not completing quickly such as network or console I/O.

writing correct concurrent programs is primarily about managing access to shared, mutable state.
always use the proper synchronization whenever data is shared across threads.
Locking is not just about mutual exclusion; it is also about memory visibility. To ensure that all threads see the most up-to-date
values of shared mutable variables, the reading and writing threads must synchronize on a common lock.
a read of a volatile variable always returns the most recent write by any thread.
Locking can guarantee both visibility and atomicity; volatile variables can only guarantee visibility. (
the semantics of volatile are not strong enough to make the increment operation (count++) atomic
)
When an object creates a thread from its constructor, it almost always shares its this reference with the new thread, either explicitly
(by passing it to the constructor) or implicitly (because the Thread or Runnable is an inner class of the owning object). The new
thread might then be able to see the owning object before it is fully constructed. There's nothing wrong with creating a thread
in a constructor, but it is best not to start the thread immediately.

If data is only accessed from a single thread, no synchronization is needed. This technique, thread confinement,
is one of the simplest ways to achieve thread safety. Swing uses thread confinement extensively. The Swing visual components and data model
objects are not thread safe; instead, safety is achieved by confining them to the Swing event dispatch thread.
To use Swing properly, code running in threads other than the event thread should not access these objects.
(To make this easier, Swing provides the invokeLater mechanism to schedule a Runnable for execution in the event thread.)

Thread-Local provides get and set access or methods that maintain a separate copy of the value for each thread that uses it,
so a get returns the most recent value passed to set from the currently executing thread.

private static ThreadLocal<Connection> connectionHolder
    = new ThreadLocal<Connection>() {
        public Connection initialValue() {
            return DriverManager.getConnection(DB_URL);
        }
    };

public static Connection getConnection() {
    return connectionHolder.get();
}

Immutable objects are always thread-safe.
Immutable objects are simple. They can only be in one state, which is carefully controlled by the constructor.
An object whose fields are all final may still be mutable, since final fields can hold references to mutable objects.
Final fields can't be modified (although the objects they refer to can be modified if they are mutable)
Just as it is a good practice to make all fields private unless they need greater visibility [EJ Item 12], it is a good practice to make
all fields final unless they need to be mutable.

The synchronized collections (wrapper by the Collections.synchronizedXxx factory methods) are thread-safe. With a synchronized collection, these
compound actions are still technically thread-safe even without client-side locking, but they may not behave as you might expect when other
threads can concurrently modify the collection.

public static Object getLast(Vector list) {
    int lastIndex = list.size() - 1;
    return list.get(lastIndex);
}

public static void deleteLast(Vector list) {
    int lastIndex = list.size() - 1;
    list.remove(lastIndex);
}

To:

public static Object getLast(Vector list) {
    synchronized (list) {
        int lastIndex = list.size() - 1;
        return list.get(lastIndex);
    }
}

public static void deleteLast(Vector list) {
    synchronized (list) {
        int lastIndex = list.size() - 1;
        list.remove(lastIndex);
    }
}

List<Widget> widgetList
    = Collections.synchronizedList(new ArrayList<Widget>());
...
// May throw ConcurrentModificationException
for (Widget w : widgetList)
    doSomething(w);

An alternative to locking the collection during iteration is to clone the collection and iterate the copy instead.
Replacing synchronized collections with concurrent collections can offer dramatic scalability improvements with little risk.
Java 5.0 adds ConcurrentHashMap, a replacement for synchronized hash-based Map implementations, and CopyOnWriteArrayList,
a replacement for synchronized List implementations for cases where traversal is the dominant operation.

BlockingQueue extends Queue to add blocking insertion and retrieval operations. If the queue is empty, a retrieval blocks until
an element is available, and if the queue is full (for bounded queues) an insertion blocks until there is space available.
Blocking queues are extremely useful in producer-consumer designs

Just as ConcurrentHashMap is a concurrent replacement for a synchronized hash-based Map, Java 6 adds ConcurrentSkipListMap
and ConcurrentSkipListSet, which are concurrent replacements for a synchronized SortedMap or SortedSet (such as treeMap
or TReeSet wrapped with synchronizedMap).

ConcurrentHashMap, along with the other concurrent collections, further improve on the synchronized collection classes by providing
iterators that do not throw ConcurrentModificationException, thus eliminating the need to lock the collection during iteration.
The iterators returned by ConcurrentHashMap are weakly consistent instead of fail-fast. A weakly consistent iterator can
tolerate concurrent modification, traverses elements as they existed when the iterator was constructed, and may (but is not
guaranteed to) reflect modifications to the collection after the construction of the iterator.

Since the result of size could be out of date by the time it is computed, it is really only an estimate, so size
is allowed to return an approximation instead of an exact count.

The one feature offered by the synchronized Map implementations but not by ConcurrentHashMap is the ability to lock the map
 for exclusive access. With Hashtable and synchronizedMap, acquiring the Map lock prevents any other thread from accessing it.
Because it has so many advantages and so few disadvantages compared to Hashtable or synchronizedMap, replacing synchronized Map
implementations with ConcurrentHashMap in most cases results only in better scalability. Only if your application needs to
lock the map for exclusive access [3] is ConcurrentHashMap not an appropriate drop-in replacement.

CopyOnWriteArrayList is a concurrent replacement for a synchronized List that offers better concurrency in some common situations
and eliminates the need to lock or copy the collection during iteration. (Similarly, CopyOnWriteArraySet is a concurrent
replacement for a synchronized Set.) They implement mutability by creating and republishing a new copy of the collection every time it is modified.

Obviously, there is some cost to copying the backing array every time the collection is modified, especially if the collection is large; the copy-on-write
collections are reasonable to use only when iteration is far more common than modification. This criterion exactly describes many
event-notification systems: delivering a notification requires iterating the list of registered listeners and calling each
one of them, and in most cases registering or unregistering an event listener is far less common than receiving an event notification.

Java 6 also adds another two collection types, Deque (pronounced "deck") and BlockingDeque, that extend Queue and BlockingQueue.
A Deque is a doubleended queue that allows efficient insertion and removal from both the head and the tail. Implementations
include ArrayDeque and LinkedBlockingDeque.

A producerconsumer design has one shared work queue for all consumers; in a work stealing design, every consumer has its own deque.
If a consumer exhausts the work in its own deque, it can steal work from the tail of someone else's deque. Work stealing can
be more scalable than a traditional producer-consumer design because workers don't contend for a shared work queue; most of
the time they access only their own deque, reducing contention. When a worker has to access another's queue, it does so from
the tail rather than the head, further reducing contention.

a blocked thread must wait for an event that is beyond its control before it can proceed.
The put and take methods of BlockingQueue throw the checked InterruptedException, as do a number of other library methods such as
Thread.sleep. When a method can throw InterruptedException, it is telling you that it is a blocking method, and further that
if it is interrupted, it will make an effort to stop blocking early.

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 pointif it feels like it. While there is nothing in the API or language specification that demands any specific
application-level semantics for interruption, the most sensible use for interruption is to cancel an activity. Blocking
methods that are responsive to interruption make it easier to cancel long-running activities on a timely basis.

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:
Propagate the InterruptedException. This is often the most sensible policy if you can get away with itjust 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
public class TaskRunnable implements Runnable {
    BlockingQueue<Task> queue;
    ...
    public void run() {
        try {
            processTask(queue.take());
        } catch (InterruptedException e) {
             // restore interrupted status
             Thread.currentThread().interrupt();
        }
    }
}


A synchronizer is any object that coordinates the control flow of threads based on its state. Blocking queues can act as synchronizers;
other types of synchronizers include semaphores, barriers, and latches.

A latch acts as a gate: until the latch reaches the terminal state the gate is closed and no thread can pass, and in the terminal state
the gate opens, allowing all threads to pass. Once the latch reaches the terminal state, it cannot change state again, so it remains
open forever. Latches can be used to ensure that certain activities do not proceed until other one-time activities complete
CountDownLatch is a flexible latch implementation that can be used in any of these situations; it allows one or more threads to
wait for a set of events to occur. The latch state consists of a counter initialized to a positive number, representing
the number of events to wait for. The countDown method decrements the counter, indicating that an event has occurred, and
the await methods wait for the counter to reach zero, which happens when all the events have occurred. If the counter is nonzero
on entry, await blocks until the counter reaches zero, the waiting thread is interrupted, or the wait times out.

FutureTask also acts like a latch. (FutureTask implements Future, which describes an abstract result-bearing computation [CPJ 4.3.3].)
A computation represented by a FutureTask is implemented with a Callable, the result-bearing equivalent of Runnable, and can be in
one of three states: waiting to run, running, or completed. Completion subsumes all the ways a computation can complete, including
normal completion, cancellation, and exception. Once a FutureTask enters the completed state, it stays in that state forever.

FutureTask is used by the Executor framework to represent asynchronous tasks, and can also be used to represent any potentially
lengthy computation that can be started before the results are needed.

Semaphores are useful for implementing resource pools such as database connection pools. While it is easy to construct a fixed-sized pool
that fails if you request a resource from an empty pool, what you really want is to block if the pool is empty and unblock when it
becomes nonempty again. If you initialize a Semaphore to the pool size, acquire a permit before trying to fetch a resource from the
pool, and release the permit after putting a resource back in the pool, acquire blocks until the pool becomes nonempty.

Barriers are similar to latches in that they block a group of threads until some event has occurred [CPJ 4.4.3]. The key difference is that
with a barrier, all the threads must come together at a barrier point at the same time in order to proceed. Latches are for waiting
for events; barriers are for waiting for other threads.

CyclicBarrier allows a fixed number of parties to rendezvous repeatedly at a barrier point and is useful in parallel iterative algorithms
that break down a problem into a fixed number of independent subproblems. Threads call await when they reach the barrier point,
and await blocks until all the threads have reached the barrier point. If all threads meet at the barrier point, the barrier has
been successfully passed, in which case all threads are released and the barrier is reset so it can be used again.

When there are more runnable threads than available processors, threads sit idle. Having many idle threads can tie up a lot of memory,
putting pressure on the garbage collector, and having many threads competing for the CPUs can impose other performance costs as well.
java.util.concurrent provides a flexible thread pool implementation as part of the Executor framework. The primary abstraction for
task execution in the Java class libraries is not Thread, but Executor

Whenever you see code of the form:
new Thread(runnable).start()
and you think you might at some point want a more flexible execution policy, seriously consider replacing it with the use of an Executor.
An Executor implementation is likely to create threads for processing tasks. But the JVM can't exit until all the (nondaemon)
threads have terminated, so failing to shut down an Executor could prevent the JVM from exiting.
the ExecutorService interface extends Executor, adding a number of methods for lifecycle management (as well as some convenience
methods for task submission).
Timer has some drawbacks, and ScheduledThreadPoolExecutor should be thought of as its replacement
Runnable is a fairly limiting abstraction; run cannot return a value or throw checked exceptions
To express a non-value-returning task with Callable, use Callable<Void>.
In the Executor framework, tasks that have been submitted but not yet started can always be cancelled, and tasks that
have started can sometimes be cancelled if they are responsive to interruption.
Future represents the lifecycle of a task and provides methods to test whether the task has completed or been cancelled,
retrieve its result, and cancel the task.
The submit methods in ExecutorService all return a Future, so that you can submit a Runnable or a Callable to an executor and
get back a Future that can be used to retrieve the result or cancel the task.
CompletionService combines the functionality of an Executor and a BlockingQueue. You can submit Callable tasks to it for execution
and use the queuelike methods take and poll to retrieve completed results

If you've tried to write even a simple GUI application using Swing, you know that GUI applications have their own peculiar
threading issues. To maintain safety, certain tasks must run in the Swing event thread. But you cannot execute longrunning tasks
in the event thread, lest the UI become unresponsive. And Swing data structures are not thread-safe, so you must be careful to
confine them to the event thread.

Nearly all GUI toolkits, including Swing and SWT, are implemented as singlethreaded subsystems in which all GUI activity is confined to a single thread.
Single-threaded GUI frameworks achieve thread safety via thread confinement; all GUI objects, including visual components and data models, are
accessed exclusively from the event thread.
Because there is only a single thread for processing GUI tasks, they are processed sequentiallyone task finishes before the next one
begins, and no two tasks overlap. Knowing this makes writing task code easieryou don't have to worry about interference from other tasks.
tasks that execute in the event thread must return control to the event thread quickly.
To initiate a longrunning task you must run that task in another thread so control can return quickly to the event thread.
To update a progress indicator while a long-running task executes or provide visual feedback when it completes, you again need to
execute code in the event thread. This can get complicated quickly.
The Swing single-thread rule: Swing components and models should be created, modified, and queried only from the event-dispatching thread.
SwingUtilities.invokeLater, which schedules a Runnable for execution on the event thread (callable from any thread);
SwingUtilities.invokeAndWait, which schedules a Runnable task for execution on the event thread and blocks the current thread until it
completes (callable only from a non-GUI thread);

A program will be free of lock-ordering deadlocks if all threads acquire the locks they need in a fixed global order.
Invoking an alien method with a lock held is asking for liveness trouble. The alien method might acquire other locks (risking deadlock)
or block for an unexpectedly long time, stalling other threads that need the lock you hold.
Strive to use open calls throughout your program. Programs that rely on open calls are far easier to analyze for deadlock-freedom
than those that allow calls to alien methods with locks held
Tasks that wait for the results of other tasks are the primary source of thread-starvation deadlock;
A program that never acquires more than one lock at a time cannot experience lock-ordering deadlock.
try to minimize the number of potential locking interactions, and follow and document a lock-ordering protocol for locks that may be acquired together.
Using open calls wherever possible.
Where intrinsic locks wait forever if they cannot acquire the lock, explicit locks let you specify a timeout after which tryLock returns failure. By using a
timeout that is much longer than you expect acquiring the lock to take, you can regain control when something unexpected happens.

To trigger a thread dump, you can send the JVM process a SIGQUIT signal (kill -3) on Unix platforms, or press the Ctrl-\ key on Unix or
Ctrl-Break on Windows platforms.
There's nothing in the JDBC specification that requires a Connection to be thread-safe, and it is common to confine use of a Connection
to a single thread, as was intended here.

Starvation occurs when a thread is perpetually denied access to resources it needs in order to make progress;
Improving performance means doing more work with fewer resources.
The major challenge in constructing tests for concurrent programs is that potential failures may be rare probabalistic occurrences rather than
deterministic ones; tests that disclose such failures must be more extensive and run for longer than typical sequential tests.

Unfortunately, test code can introduce timing or synchronization artifacts that can mask bugs that might otherwise manifest themselves

Done.



Friday, January 17, 2014

Schedules a task run within a period (with start time and end time)

package scheduler;

import java.util.logging.Logger;

public class PeriodTaskTest {

private static Logger log = Logger.getLogger(PeriodTaskTest.class.getName());

public static void main(String[] args) {
log.info("Main started.");
new AlarmTask(9, 22, 0,9,24,0,10*1000).activateThenStop();
   log.info("Main ended.");
}

}

class AlarmTask extends PeriodTask{
private int fCount;
private Logger log = Logger.getLogger(AlarmTask.class.getName());

public AlarmTask(int startHour,int startMin,int startSec,int endHour,int endMin,int endSec,long aDelayBetween) {
super(startHour,startMin,startSec,endHour,endMin,endSec,aDelayBetween);
}

@Override
final protected void execute() {
     ++fCount;
     log.info("beep " + fCount);
}

}



package scheduler;

import java.util.Calendar;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.TimeUnit;
import java.util.logging.Logger;

public abstract class PeriodTask implements Runnable {

private Logger log = Logger.getLogger("Auspix");
private final ScheduledExecutorService fScheduler;
private final long fInitialDelay;
private final long fDelayBetweenRuns;
private final long fShutdownAfter;
private static final int NUM_THREADS = 2;
private static final boolean DONT_INTERRUPT_IF_RUNNING = false;

@Override
public void run() {
execute();
}

public PeriodTask(int startHour,int startMin,int startSec,int endHour,int endMin,int endSec,long aDelayBetween){
log.info(String.format("Will start on %s and end on %s every %s seconds.", startHour+":"+startMin+":"+startSec,endHour+":"+endMin+":"+endSec,aDelayBetween));
Calendar calStart = getCal(startHour,startMin,startSec);
Calendar calEnd = getCal(endHour,endMin,endSec);
long aInitialDelay = calStart.getTimeInMillis() - System.currentTimeMillis();
long aStopAfter = calEnd.getTimeInMillis() - System.currentTimeMillis();
log.info(String.format("start time is %tT, end time is %tT. Initial delay is %d, will stop after %d.",calStart.getTime(),calEnd.getTime(),aInitialDelay,aStopAfter));
fInitialDelay = aInitialDelay;
fDelayBetweenRuns = aDelayBetween;
fShutdownAfter = aStopAfter;
fScheduler = Executors.newScheduledThreadPool(NUM_THREADS);
}

private Calendar getCal(int startHour, int startMin, int startSec) {
Calendar cal = Calendar.getInstance();
cal.set(Calendar.HOUR_OF_DAY, startHour);
cal.set(Calendar.MINUTE, startMin);
cal.set(Calendar.SECOND,startSec);
return (Calendar)cal.clone();
}

public void activateThenStop() {
ScheduledFuture<?> actionFuture = fScheduler.scheduleAtFixedRate(this,
fInitialDelay, fDelayBetweenRuns, TimeUnit.MILLISECONDS);
Runnable stopAlarm = new StopTask(actionFuture);
fScheduler.schedule(stopAlarm, fShutdownAfter, TimeUnit.MILLISECONDS);
}

protected abstract void execute();

private final class StopTask implements Runnable {
private ScheduledFuture<?> fSchedFuture;
private Logger log = Logger.getLogger("Auspix");

public StopTask(ScheduledFuture<?> aSchedFuture) {
fSchedFuture = aSchedFuture;
}

@Override
public void run() {
log.info("Stopping .");
fSchedFuture.cancel(DONT_INTERRUPT_IF_RUNNING);
fScheduler.shutdown();
}

}

}

Redirect the output to Java Swing textarea

The below example will redirect the System.out to Java Swing text area. If want to redirect java.util.logging.Logger to Java Swing text area. Need override ConsoleHandler to setOutputStream(System.err); to setOutputStream(System.out);

Or update System.setOut(new PrintStream(new PipedOutputStream(outPipe), true));
to System.setErr(new PrintStream(new PipedOutputStream(outPipe), true));

package gui;

import java.awt.BorderLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.IOException;
import java.io.PipedInputStream;
import java.io.PipedOutputStream;
import java.io.PrintStream;
import java.util.List;
import java.util.Scanner;
import java.util.logging.Logger;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JTextArea;
import javax.swing.SwingWorker;

public class JConsole {

private static Logger logger = Logger.getLogger(JConsole.class.getName());

public static void main(String[] args) throws IOException {
JFrame frame = new JFrame("JConsole");
JTextArea jta = new JTextArea();
JButton button = new JButton("Run");
frame.setLayout(new BorderLayout());
frame.add(button,BorderLayout.NORTH);
frame.add(jta,BorderLayout.CENTER);
button.addActionListener(new ActionListener(){
@Override
public void actionPerformed(ActionEvent e) {
new SwingWorker<Void, Object>(){
@Override
protected Void doInBackground() throws Exception {
outputTest("inner");
return null;
}}.execute();
}});

frame.setSize(400, 300);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
console(jta);
}

public static void outputTest(String msg){
for(int i=0;i<10;i++){
System.out.println(i+" "+msg);
logger.info("Test "+i);
try {
Thread.sleep(500);
} catch (InterruptedException ex) {
ex.printStackTrace();
}
}
}

public static void console(final JTextArea area) throws IOException {
final PipedInputStream outPipe = new PipedInputStream();
System.setOut(new PrintStream(new PipedOutputStream(outPipe), true));
new SwingWorker<Void, String>() {
@Override
protected Void doInBackground() throws Exception {
Scanner s = new Scanner(outPipe);
while (s.hasNextLine()){
String line = s.nextLine();
publish(line + "\n");
}
s.close();
return null;
}

@Override
protected void process(List<String> chunks) {
for (String line : chunks){
area.append(line);
}
}
}.execute();
}

}

Thursday, January 16, 2014

English

compelling yourself to face what you fear and working on turning those fears into assets

Monday, January 13, 2014

Effective Java 2 Review

Item 6 Eliminate obsolete object references
a single-element enum type is the best way to implement a singleton.
whenever a class manages its own memory, the programmer
should be alert for memory leaks. Whenever an element is freed, any
object references contained in the element should be nulled out. (Stack elements for example)
Another common source of memory leaks is caches.
WeakHashMap is useful only if the desired lifetime of cache
entries is determined by external references to the key, not the value. (Help to eliminate memory leaks)
WeakReferences are cleared agressively; SoftReferences are not. Using a SoftReference tells the garbage collector that you would like it to keep the object
around for a while, until memory considerations cause it to reclaim the object.
By contrast, using a WeakReference tells the garbage collector that there's no reason to keep the object around any longer than necessary.
A third common source of memory leaks is listeners and other callbacks.
The best way to
ensure that callbacks are garbage collected promptly is to store only weak references
to them, for instance, by storing them only as keys in a WeakHashMap.

Item 7: Avoid finalizers
Just provide
an explicit termination method, and require clients of the class to invoke this
method on each instance when it is no longer needed.
don’t use finalizers except as a safety net or to terminate
noncritical native resources. In those rare instances where you do use a finalizer,
remember to invoke super.finalize.

Item 9: Always override hashCode when you override equals
You
must override hashCode in every class that overrides equals. equal objects must have equal hash codes.


To recap, all classes that implement Cloneable should override clone with a
public method whose return type is the class itself. This method should first call
super.clone and then fix any fields that need to be fixed. some
expert programmers simply choose never to override the clone method and never
to invoke it except, perhaps, to copy arrays. A fine approach to object copying is to provide a copy constructor or copy
factory.

Why wait and notify are in Object?
wait and notify are communication mechanism between two thread.
Locks are made available on per Object basis,
In Java all object has a monitor. Threads waits on monitors so, to perform a wait, we need 2 parameters:
- a Thread
- a monitor (any object)

In the Java design, the thread can not be specified, it is always the current thread running the code. However, we can specify the monitor
(which is the object we call wait on). This is a good design, because if we could make any other thread to wait on a desired monitor,
this would lead to an "intrusion", posing difficulties on designing/programming concurrent programs. Remember that in Java all operations that are
intrusive in another thread's execution are deprecated (e.g. stop()).
why wait and notify method in object because threads wait for lock and lock is implemented on Object level. its as simple as this.


make each class or member as inaccessible as
possible.
package-private—The member is accessible from any class in the package
where it is declared. Technically known as default access
protected—The member is accessible from subclasses of the class where it is
declared
Instance fields should never be public.
it is wrong for a class
to have a public static final array field, or an accessor that returns such a
field. If a class has such a field or accessor, clients will be able to modify the contents
of the array.
There are two ways to fix the
problem. You can make the public array private and add a public immutable list.
Alternatively, you can make the array private and add a public method that
returns a copy of a private array:
if a class is package-private or is a private nested class, there is
nothing inherently wrong with exposing its data fields

An immutable class is simply a class whose instances cannot be modified. All of
the information contained in each instance is provided when it is created and is
fixed for the lifetime of the object. The Java platform libraries contain many
immutable classes, including String.
Immutable objects are inherently thread-safe; they require no synchronization.
The only real disadvantage of immutable classes is that they require a
separate object for each distinct value.
You
should always make small value objects, such as PhoneNumber and Complex,
immutable.(There are several classes in the Java platform libraries, such as java.util.Date and java.awt.Point, that should have been immutable but
aren’t.)
If a class cannot
be made immutable, limit its mutability as much as possible.

What are the differences between Maps returned by Collections.synchronizedMap(Map) and ConcurrentHashMap
ConcurrentHashMap does not allow null keys or values.

With generics, you tell the compiler
what types of objects are permitted in each collection. The compiler inserts casts
for you automatically and tells you at compile time if you try to insert an object of
the wrong type.

Since release
1.5, Java has provided a safe alternative known as unbounded wildcard types. If
you want to use a generic type but you don’t know or care what the actual type
parameter is, you can use a question mark instead. For example, the unbounded
wildcard type for the generic type Set<E> is Set<?> (read “set of some type”).

There are two minor exceptions to the rule that you should not use raw types
in new code, both of which stem from the fact that generic type information is
erased at runtime. You must use raw types in class literals.
In other words, List.class,
String[].class, and int.class are all legal, but List<String>.class and
List<?>.class are not. The second exception to the rule concerns the instanceof operator. Because
generic type information is erased at runtime, it is illegal to use the instanceof
operator on parameterized types other than unbounded wildcard types.
In summary, using raw types can lead to exceptions at runtime, so don’t use
them in new code.
As a quick review,
Set<Object> is a parameterized type representing a set that can contain objects of
any type, Set<?> is a wildcard type representing a set that can contain only
objects of some unknown type, and Set is a raw type, which opts out of the
generic type system. The first two are safe and the last is not.
Unbounded wildcard type List<?>
Bounded type parameter <E extends Number>
Recursive type bound <T extends Comparable<T>>
Bounded wildcard type List<? extends Number>  Iterable of some subtype of E
Collection<? super E> collection of some supertype of E
PECS stands for producer-extends, consumer-super.
Generic method static <E> List<E> asList(E[] a)

Prefer lists to arrays
Arrays differ from generic types in two important ways. First, arrays are covariant.
This scary-sounding word means simply that if Sub is a subtype of Super, then the
array type Sub[] is a subtype of Super[]. Generics, by contrast, are invariant: for
any two distinct types Type1 and Type2, List<Type1> is neither a subtype nor a
supertype of List<Type2>. You might think this
means that generics are deficient, but arguably it is arrays that are deficient.
// Fails at runtime!
Object[] objectArray = new Long[1];
objectArray[0] = "I don't fit in"; // Throws ArrayStoreException
but this one is not:
// Won't compile!
List<Object> ol = new ArrayList<Long>(); // Incompatible types
ol.add("I don't fit in");
The second major difference between arrays and generics is that arrays are
reified [JLS, 4.7]. This means that arrays know and enforce their element types at
runtime. As noted above, if you try to store a String into an array of Long, you’ll
get an ArrayStoreException. Generics, by contrast, are implemented by erasure
[JLS, 4.6]. This means that they enforce their type constraints only at compile
time and discard (or erase) their element type information at runtime. Erasure is
what allows generic types to interoperate freely with legacy code that does not use
generics
For example, it is illegal to create an array of a generic type, a parameterized
type, or a type parameter.
When you get a generic array creation error, the best solution is often to use
the collection type List<E> in preference to the array type E[].You might sacrifice
some performance or conciseness, but in exchange you get better type safety
and interoperability.

The type parameter list, which declares the type parameter, goes between the
method’s modifiers and its return type. In this example, the type parameter list
is <E> and the return type is Set<E>.
// Generic method
public static <E> Set<E> union(Set<E> s1, Set<E> s2) {
Set<E> result = new HashSet<E>(s1);
result.addAll(s2);
return result;
}

Comparables are
always consumers, so you should always use Comparable<? super T> in preference
to Comparable<T>. The same is true of comparators, so you should always
use Comparator<? super T> in preference to Comparator<T>.

The Java programming language provides three kinds of throwables: checked exceptions,
runtime exceptions, and errors.
use checked exceptions for conditions from which the caller
can reasonably be expected to recover. By throwing a checked exception, you
force the caller to handle the exception in a catch clause or to propagate it outward.
There are two kinds of unchecked throwables: runtime exceptions and errors.
They are identical in their behavior: both are throwables that needn’t, and generally
shouldn’t, be caught.
If a program throws an unchecked exception or an error,
it is generally the case that recovery is impossible and continued execution would
do more harm than good. ArrayIndexOutOfBoundsException
While the Java Language Specification does not require it, there is a strong
convention that errors are reserved for use by the JVM to indicate resource deficiencies,
invariant failures, or other conditions that make it impossible to continue
execution. Given the almost universal acceptance of this convention, it’s best not
to implement any new Error subclasses. Therefore, all of the unchecked throwables
you implement should subclass RuntimeException (directly or indirectly).

Not only does synchronization
prevent a thread from observing an object in an inconsistent state, but it
ensures that each thread entering a synchronized method or block sees the effects
of all previous modifications that were guarded by the same lock.
The consequences of failing to synchronize access to shared mutable data can
be dire even if the data is atomically readable and writable.


Sunday, January 12, 2014

近视逆转

1. 做眼保健操
2. 少带眼镜
3. 多看远
4. 用眼睛写米字
其实写"米"很简单,简单的说让你的眼球360度大转弯! "米"有6个笔画,你就把每个笔画用眼睛在空中写,并且尽可能的伸展你的视角就可以了

  《The Cure OfImperfect Sight By Treatment WithoutGlasses》(《不戴眼镜的完美的视力》) 
  贝茨原著,其实和上面的《Easy摘掉眼镜恢复视力》、《改善你的视力-跟眼镜说再见》内容基本一样。 

http://bbs.tianya.cn/post-no11-950810-1.shtml
自己治疗近视眼

http://wenwen.soso.com/z/q216728661.htm

我魏碧慧最美丽的日记

http://www.douban.com/note/89706798/


中学生近视之祸首--戴近视镜!

http://emsonyin.blogbus.com/logs/200624132.html

不知道你们治疗近视的,但是我的确自愈了(方法内详)

http://tieba.baidu.com/p/1183708910

Saturday, January 11, 2014

清蒸青斑

1. 1.5磅左右游水青斑一条,洗净后滤15分钟
2. 葱一段、姜一块切成丝
3. 在鱼背上拉几道口子,将葱姜塞入鱼腹及盘底,在鱼背口子上洒满盐,倒上料酒生抽腌15分钟
4. 蒸锅水开后,将鱼放入蒸8分钟。关火闷1分钟,淋上炸花椒和蒸鱼豉油

射雕英雄传 少儿版 风雪惊变

射雕英雄传 少儿版 风雪惊变

1. 说书先生说书,郭啸天和杨铁心请去喝酒打听北方情况。岳爷爷、跛子曲三
2. 郭杨雪夜聚会遇到丘处机,获赠匕首和名字。丘处机药石、诗、武艺。包救人
3. 郭杨被官兵包围,郭杨逃,段天德脸有刀疤和青记。包惜弱被黑衣男子严烈救,朝北方走。

Tuesday, January 7, 2014

Java Web Service: Up and running

Java Web Service: Up and running
1. Source code:
http://www.oreilly.com/catalog/9780596521127
2. Chap 1
a SOAP-based service delivered over HTTP is a special case of a REST-style service.
web services play a central role in the SOA approach to software design and development.
REST stands for REpresentational State Transfer.
Language transparency is the key to web service interoperability;
JAX-WS (Java API for XML-Web Service) supports SOAP based and REST style service. JAX-WS is commonly shorten to JWS for Java Web Services.
JAX-WS preserves but also significantly extends the capabilities of JAX-RPC.
A SOAP-based web service could be implemented as a single Java class but, following
best practices, there should be an interface that declares the methods, which are the
web service operations, and an implementation, which defines the methods declared
in the interface. The interface is called SEI: Service Endpoint Interface. The implementation is called the SIB: Service Implementation Bean. The SIB
can be either a POJO or a Stateless EJB.

WSDL is pronounced "whiz dull".
The core Java utility is now called wsimport but the earlier names wsdl2java and java2wsdl were more descriptive

On the web service side, the underlying Java libraries process the HTTP request (the SOAP envelope is the body of an HTTP message), extract
the SOAP envelope, determine the identity of the requested service operation, invoke
the corresponding Java method getTimeAsString, and then generate the appropriate
SOAP message to carry the method’s return value back to the client.

In SOAP-based web services, the XML Schema type system
is the default type system that mediates between the client’s types and the service’s
types.

@SOAPBinding(style = Style.RPC)
This annotation requires that the service use only very simple types such as string and
integer. By contrast, the Teams service uses richer data types, which means that
Style.DOCUMENT, the default, should replace Style.RPC.

If the @WebResult annotation were applied, say, only to the getTimeAsString
operation, then the SOAP response for this operation would use the time_response tag
but the response for the getTimeAsElapsed operation still would use the default
return tag.
there is usually no need for programmer-generated code to use the @WebResult
annotation.

The wsimport tool reads a WSDL and generates all the required artifacts for web service development, deployment, and invocation.
The wsgen tool reads an existing web service implementation class (SIB) and generates the required JAX–WS portable artifacts for
web service development and deployment. The wsgen tool can be used for bottoms-up approach, where you are starting from a service
endpoint implementation (SIB) rather than a wsdl.

JWS still supports both rpc and document styles, with document as the default
If and when an ItemSearchResponse comes from the E-Commerce service, the method
handleResponse in the MyHandler class executes as a separate thread and prints out the
books’ titles.


REST and SOAP are quite different. SOAP is a messaging protocol, whereas REST is a
style of software architecture for distributed hypermedia systems; that is, systems in
which text, graphics, audio, and other media are stored across a network and interconnected
through hyperlinks. The World Wide Web is the obvious example of such
a system.

In a RESTful request/response service, the service response is raw XML but the incoming
request might not be XML at all. A GET request does not have a body; hence,
arguments sent as part of the request occur as attributes in the query string, a collection
of key/value pairs. Here is a sample:
http://www.onlineparlor.com/bets?horse=bigbrown&jockey=kent&amount=25

// There are two ServiceModes: PAYLOAD, the default, signals that the service
// wants access only to the underlying message payload (e.g., the
// body of an HTTP POST request); MESSAGE signals that the service wants
// access to entire message (e.g., the HTTP headers and body).
@ServiceMode(value = javax.xml.ws.Service.Mode.MESSAGE)

In the symmetric approach, the same key—called the secret
key or the single key—is used to encrypt and decrypt (see Figure 5-4). The symmetric
approach has the advantage of being relatively fast, but the disadvantage of what is
known as the key distribution problem. How is the secret key itself to be distributed
to the sender and the receiver?

In the asymmetric approach, the starting point is a key pair, which consists of a private
key and a public key. As the names suggest, the private key should not be distributed
but safeguarded by whoever generated the key pair. The public key can be distributed
freely and publicly. If message bits are encrypted with the public key, they can be decrypted
only with the private key, and vice-versa. Figure 5-5 illustrates. The asymmetric
approach solves the key distribution problem, but asymmetric encryption and decryption
are roughly a thousand times slower than their symmetric counterparts

Done