2014/06/27

java Fork/Join

★The fork/join framework is an implementation of the ExecutorService interface that helps you take advantage of multiple processors. It is designed for work that can be broken into smaller pieces recursively. The goal is to use all the available processing power to enhance the performance of your application.

As with any ExecutorService implementation, the fork/join framework distributes tasks to worker threads in a thread pool. The fork/join framework is distinct because it uses a work-stealing algorithm. Worker threads that run out of things to do can steal tasks from other threads that are still busy.
===>それはいいね!!



★例:

package testfork;

import java.util.Random;
import java.util.concurrent.ForkJoinPool;
import java.util.concurrent.RecursiveTask;

public class MaximumFinder extends RecursiveTask {

    private static final int SEQUENTIAL_THRESHOLD = 100;

    private final int[] data;
    private final int start;
    private final int end;

    public MaximumFinder(int[] data, int start, int end) {
        this.data = data;
        this.start = start;
        this.end = end;
    }

    public MaximumFinder(int[] data) {
        this(data, 0, data.length);
    }

    private Integer computeDirectly() {
        System.out.println(Thread.currentThread() + " computing: " + start
                + " to " + end);
        int max = Integer.MIN_VALUE;
        for (int i = start; i < end; i++) {
            if (data[i] > max) {
                max = data[i];
            }
        }
        return max;
    }

    @Override
    protected Object compute() {
        final int length = end - start;
        if (length < SEQUENTIAL_THRESHOLD) {
            return computeDirectly();
        }
        final int split = length / 2;
        final MaximumFinder left = new MaximumFinder(data, start, start + split);
        left.fork();
        final MaximumFinder right = new MaximumFinder(data, start + split, end);
        return Math.max((Integer) right.compute(), (Integer) left.join());
    }

    public static void main(String[] args) {
        // create a random data set
        final int[] data = new int[100000];
        final Random random = new Random();

        for (int i = 0; i < data.length; i++) {
            data[i] = random.nextInt(100);
        }

        // submit the task to the pool
        final ForkJoinPool pool = new ForkJoinPool(4);
        final MaximumFinder finder = new MaximumFinder(data);
        System.out.println(pool.invoke(finder));
       
    }
}


★ForkJoinPoolに入れるタスクはForkJoinTask型であるが、実際にはRecursiveTaskかRecursiveActionのいずれかから派生するのが便利である。
RecursiveTaskは戻り値のあるタスク、RecursiveActionは戻り値が無いタスクを定義するのに使う。

★Callable, RunnableをForkJoinTaskに変換するためのForkJoinTask.adapt()メソッドを使うこともできる


ForkJoinPool pool = new ForkJoinPool(
 Runtime.getRuntime().availableProcessors(),
 ForkJoinPool.defaultForkJoinWorkerThreadFactory,
 null,
true); // タスクの積み上げにFIFOモードを使用する.(通常はSTACKモード)

Why reduce the size of the Java JVM thread stack

★あれ、threadStack is out of heap...

When Java creates a new thread, it pre-allocates a fixed-size block of memory for that thread's stack. By reducing the size of that memory block, you can avoid running out of memory, especially if you have lots of threads - the memory saving is the reduction in stack size times the number of threads.

The downside of doing this is that you increase the chance of a Stack Overflow error.

Note that the thread stacks are created outside of the JVM heap, so even if there's plenty of memory available in the heap, you can still fail to create a thread stack due to running out of memory (or running out of address space, as Tom Hawtin correctly points out).

redis 試し

・can write to db automatically
・can store thing with four structures not only plain string key
=->redis can used to slove a wider range of problems
STINGS、LIST、SET、HASH、ZSET(順番あるET)

・publish/Subscribe 機能?raid,master/slave機能

・in-memory databases! write to hardDisk

Depending on how careful you want to be with your
data, append-only writing can be configured to never sync, sync once per second, or
sync at the completion of every operation.

・for most
databases, inserting rows is a very fast operation (inserts write to the end of an on-disk
file, not unlike Redis’s append-only log). But updating an existing row in a table is fairly
slow (it can cause a random read and may cause a random write).

===>何が良さそうだね。。


redis-cli
=->クライアントを起動する

set hello world
get hello
del hello

大文字と小文字は違う。。。

rpush list item
rpush list item2
rpush list item3

lrange list 0 -1 ==>全ての物を表示する
lrange list start end

lindex list 1 ==>items
lpop list==>item左側から吐き出す
==>stackだね。。。

In Redis, SETs are similar to LISTs in that
they’re a sequence of strings, but unlike
LISTs, Redis SETs use a hash table to keep
all strings unique


sadd set item1
sadd set item2
sadd set item3
smembers==>item1 item2 item3
sismember set item3
srem set item1


Whereas LISTs and SETs in Redis hold
sequences of items, Redis HASHes store a
mapping of keys to values.

HSET hashName key value
Hget hashName key
HDEL hashName key
HGETALL


The keys (called members)
are unique, and the values (called scores) are limited to floating-point numbers. ZSETs
have the unique property in Redis of being able to be accessed by member (like a
HASH), but items can also be accessed by the sorted order and values of the scores
==>得点あり score

zadd zset 333 item1
zadd zset 444 item2
zadd zset 555 item3

zrange zset 0 -1
zrange zset 0 -1 withscores
zrangebyscore zset 0 335 withscores



conn = redis.Redis()
conn.get('key')
conn.incr('key')
conn.decr('key')

★snapshots persistence
redis-cli

=>bgsave,save(専務)
dbfilename dump.rdb
dir /var/lib/redis
==>/var/lib/redis/dump.rdbで保存される
設定ファイルでの設定:
save 900 1
save 300 10
save 60 10000
==>
Redis will automatically
trigger a BGSAVE operation if 10,000 writes have occurred within 60
seconds since the last successful save has started

When Redis receives a request to shut down by the SHUTDOWN command, or it
receives a standard TERM signal, Redis will perform a SAVE


if we’re
running on a virtual machine, letting a BGSAVE occur may cause the system to pause
for extended periods of time, or may cause heavy use of system virtual memory, which
could degrade Redis’s performance to the point where it’s unusable.

★append-only file persistence

file.write();
file.flush();

ansible-playbook option

--list-tasks==>タスクの一覧
--check===>オプションを指定することで変更は行わないが、実際に実行するとこうなるという出力がされます
--step ==>one step at a time
--private-key  ==>鍵ファイルを指定して、そしてpasswordの指定がなくなる
--list-hosts
--skip-tags
--syntax-check ==->chechk the fiels and do nothing other
-t tags 指定するタグだけを実行する

2014/06/25

nginx ssl windows proxy

nginxをインストールする
=ー>nginx for window

nginx.exeを実行する
==>nginx -t **.conf  設定ファイルをテストする
http://localhost:ポート==>nginxのページが表示される=>OK



OpenSSlのwindows版をinstallする
OpenSSLをPATHに設定する
証明書を作成する
openssl genrsa -out server.key 1024 
openssl req -new -key server.key -out server.csr 
cp server.key server.key.orig
openssl rsa -in server.key.orig -out server.key 
openssl x509 -req -days 3650 -in server.csr -signkey server.key -out server.crt
 
==>
server.crt  server.csr  server.key  server.key.orig
 
 nginxの設定ファイルを修正する

# HTTPS server
    #
    server {
        listen       443;
        server_name  localhost;

        ssl                  on;
        ssl_certificate      c:/Installed/nginx/nginx-0.7.64/SSL/server.crt;
        ssl_certificate_key  c:/Installed/nginx/nginx-0.7.64/SSL/server.key;

        ssl_session_timeout  5m;

        ssl_protocols  SSLv2 SSLv3 TLSv1;
        ssl_ciphers  ALL:!ADH:!EXPORT56:RC4+RSA:+HIGH:+MEDIUM:+LOW:+SSLv2:+EXP;
        ssl_prefer_server_ciphers   on;

        location / {
            root   myhtml;
            index  index.html index.htm;
        }
    }
 
 
https://localhostでテストする
 
 
 
location / {
            # HTTPリクエストをそのままCatyサーバーに流す
            proxy_pass http://localhost:8000/; 

            # Catyサーバーにヘッダーを通じて情報を提供
            proxy_set_header X-Real-IP $remote_addr; 
            proxy_set_header X-Forwarded-Host $host;
            proxy_set_header X-Forwarded-Server $host;
            proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        }
 
====>locationで部分でproxyを設定する 
 
 
 
★
リバースプロキシ(英: Reverse proxy)または逆プロキシは、特定のサーバへの要求を必ず経由するように設置されたプロキシサーバ。一般的なプロキシとは異なり不特定多数のサーバを対象としない。リバースプロキシは、不特定多数のクライアントから寄せられる要求に対して、応答を肩代わりすることにより特定のサーバの負担を軽減したり、アクセスを制限することにより特定のサーバのセキュリティを高めたりする目的に用いられる。
例:
==>サーバーマシンのポート80番にやってきたHTTPリクエストを、nginxが、背後にいるCatyサーバーに渡してくれます。単にポート80番でサービスするだけならCatyサーバーにもできますが、複数のCatyサーバー達をうまく使い回したり、Catyサーバーが苦手な作業を肩代わりしてくれる役割をnginxに期待しているのです。
とりあえず、今のCatyサーバーはHTTPS(SSL)に対応してないので、HTTPS通信のラップ/アンラップをnginxにやらせてみることにします。 

プリントヘッドの電気接点のクリーニング

綿棒で、下から上に電気接触部とノズル周辺部を拭きます。 綿棒にインクが付着しなくなるまでクリーニングを行ってください。 必要に応じて新しい綿棒に取り替えます。

  1. プリンター本体の電気接触部のクリーニングを行います。 安全のため、プリンターの電源コードを外します。
  2. 電気接触部を下から上へ綿棒で拭いてクリーニングします。 必要に応じて新しい綿棒に取り替えます。綿棒にインク が付着しなくなるまでクリーニングを行います。

2014/06/24

ファンクションパラメータの哲学



==>必要な行為結果だけ取る。その人も要らない。
=>オブジェクト==>動作==>結果
。。。。
将函数作参数传递并不仅仅出于技上的考量。对软设计是个哲学问题。想想这样景:在index文件中,我可以将router传递进去,服器随后可以象的route函数。 
就像这样,我们传递一个西,然后服器利用西来完成一些事。那个叫路由的西,能帮我把个路由一下 
但是服器其不需要这样西。它只需要把事情做完就行,其实为了把事情做完,你根本不需要西,你需要的是作。也就是,你不需要,你需要动词 
理解了个概念里最核心、最基本的思想转换后,我自然而然地理解了函数程。

java オブジェクト指向 デメリット



所有使用Java的人都喜用例,所以以一个用例开始吧:倒垃圾。就像这样“Johnny,快去倒垃圾,他都快溢出来了!
的生活也同充斥着各种。我(食物),我从商店(商品),我坐在(凳子)上。 “(石)可能会忽 到你上,在你的)上弄一个(大包)。 即事物,想想没有了事物我会怎 但他们仅仅只是事物,比如: 意味着束或者 束本身,或者一些重物品,或者我围经常看到的事物的名字。 是一座建筑,那是一个石。任何一个小孩子都能指出名此而已。 生在名 上的 “才是最有趣的事情。
化需要作。 作是生活的料。 作甚至料以料! 竟除非你它,你是不会感到香种味道的。 不在,但是生活一直在并一直有趣的功劳还是在于动词
当然,除了名动词,我们还有形容,介,代,冠连词,和许许多多其他构造有趣言的词汇 都在言中扮演着自己的角色,而且每一个都很重要。 如果它哪一个不存在了的,那是挺憾的事情
面向
StateManager.getConsiderationSetter(“Noun Oriented Thinking”, State.HARMFUL).run()
或者, 正如外面的世界所面向名的思考是有害的
面向象的程把名放到首位,但是我们为什么非得把名捧上神以至于让语的如此啰嗦哪? 什么一种句成分的低位非得高于另外一种?并不是好 像面向象的程突然使得动词的低位降低,正如我们认为的那 是一种奇怪的认识的扭曲。 正如我的朋友 Jacob Gabrielso一次到, 提倡面向象的程好比提倡面向子的穿衣方式
Java中唯一提供的建模的工具。 所以当一个新的想法出在你海的候,你不得不重塑它,包装它,甚至弄碎它直到它成一个名 即使它开始是一个作,程,或者任何其他不是的概念。
我似乎回到了8,9年前一帮搞Perl的家伙的:,并不是所有的西都是象的。
很奇怪,Java似乎是主流面向言中唯一一个完全以名词为中心的言。 Python或者Ruby中,你不会找到 AbstractProxyMediatorNotificationStrategyFactory或者其他似的西。 什么在Java中它们满 地都是? 我敢打赌这是原因出在了动词的身上。 PythonRubyJavaScriptPerl当然,有所有的函数式言允你声明并 函数而不用用包装它Java没有理由不简单地添加第一函数并最终实现一个成熟的,没有扭曲的可以人自由运用动词实现想法的世界。 实际上,有一个基于JVM  The Nice programming language 实现了一个非常Java法, 并包含了一个非常具有表力的实现了使用 动词方式:独立函数。 Java制你用CallbackRuunable或其他匿名接口来包装它一个以便于用。

Sun
公司甚至没有打破他一切函数都必类拥有的信条。 任何匿名的函数都会具有一个式的this指向定它的问题解决了