ForkJoinPool 과  ThreadPoolExecutor 이 대표적으로 ExecutorService를 구현한 class 이다.



  => Executor는 여기참고 : 참고2   참고사이트

     Executor<-ExecutorService관계이며,  Excutor가 Runnable를 실행하고,  ExecutorService 에서  shutdown등으로 관리가능.

     
    (이렇게 Factory 형태로도 많이 쓰인다)  

     ExecutorService pool Executors(유틸).newFixedThreadPool (thread num)  returns ExecutorSerivce.

                                             => newFixedThreadPool을 이용한 서버소켓 accept 예제.

     pool.execute ( request ); //Executor   REF

     pool.shutdown() or submit() or blabla; //ExecutorService


    ==> 참고2 사이트: pool.submit (Callable )으로 실행되지만, 실제 Callable.call이 언제실행될지 모르므로
          Executor은 Future를 리턴.   future . get()  : (blocking임)으로 값가져 옴. 


=============ForkJoin Pool==========

ForkJoinPool에 RecursiveAction구현 객체를 invoke 하면


객체의 compute 함수가 실행되면서

compute 내에 구현된 InvokeAll(work1,work2)를 통해 멀티코어를 실행하게 된다.




<<<    Factorial을 이용한 ForkJoinPool 예제 >>


public class TestPool {


public static void main(String[] args){

ForkJoinPool pool = new ForkJoinPool();

long time1 = System.currentTimeMillis();

for(int i=0; i<500000;i++){

MyWork myWork = new MyWork(25);  //25factorial

pool.invoke(myWork);

}

long time2 = System.currentTimeMillis();

System.out.println("Elapse:" + (time2-time1));

}

}


class MyWork extends RecursiveAction{  

int base=0;

int to=1;

long result=1;

//factorial

public MyWork(int base){

this.base = base;

}

//half factorial

public MyWork(int base, int to){

this.base = base;

this.to = to;

}

@Override

protected void compute() {

//////small value Calculate and return

if ( base-to <= 2 ){

System.out.println("END: base,to:" + base +","+to);

for ( int i=base; i >= to; i-- )

result = result*i;

return;

}


       //////large value DIVIDE as 2 works.///////////////

int median = to+ (base-to)/2;

MyWork w1 = new MyWork(base, median+1);

MyWork w2 = new MyWork(median, to);

invokeAll( w1, w2);  //waiting....  then why USE RecursiveTask(which resturns VALUE)

result = w1.result * w2.result;

System.out.println("FINAL RESULT:" + result);

}

}



Posted by yongary
,

<JDK 1.4>


(Selectable)Channel 

    has

Selector

    has

SelectionKey  인데  Selector를 서버채널과 클라이언트 채널에 동시에 등록해 accept와 read동시 수행 가능.




<JDK1.6 >의 

 java.nio.channels.SelectorProvider 는 linux시스템의 epoll을 구현.   select=O(n),  epoll=O(1)

    nio = non-blocking io 임. 


=========Selector 예제===== 서버 thread=====

//nio version

public void run(){

ServerSocketChannel ssc=null;

try{

        //for SSC

InetSocketAddress addr = new InetSocketAddress(1990);

ssc = ServerSocketChannel.open();

ssc.socket().bind(addr);

//for Selector

Selector selector=Selector.open();

ssc.configureBlocking(false); //make nonBlocking accept()

ssc.register(selector, SelectionKey.OP_ACCEPT);

while (true){ //select for accept While

int numKeys = selector.select(); //select is non Blocking.

if (numKeys > 0){

//System.out.print(" numKeys:" + numKeys); //too much call

Set<SelectionKey> keySet = selector.selectedKeys(); /// Must be selectedKeys.

Iterator<SelectionKey> it = keySet.iterator();

while( it.hasNext()) {

  SelectionKey key = it.next();

  if( (key.readyOps() & SelectionKey.OP_ACCEPT)==SelectionKey.OP_ACCEPT){


SocketChannel csc = ((ServerSocketChannel) key.channel()).accept();

csc.configureBlocking(false);

System.out.println("    [Server] Client Connected ------"+csc);

//read Key register

csc.register(selector,  SelectionKey.OP_READ);

it.remove();//delete key

  }else if( (key.readyOps() & SelectionKey.OP_READ)==SelectionKey.OP_READ){

SocketChannel csc =  (SocketChannel) key.channel();

//System.out.println("    [Server]  Client READ Event ------"+csc);

readFromClient(csc);

it.remove();//delete key

     }

           }

         }

        Thread.sleep(10);

       } //while

}catch (Exception e){

    e.printStackTrace();

}finally{

      try{ 

           if(ssc!=null) ssc.close(); 

      }catch (IOException e){}

       }

}//run

Posted by yongary
,

Generics: - casting으로부터의 해방.

List<String>, 

List<?>  ?: any type extends Object

Class<?>  :  (Object).getClass()로 리턴되는 특정 class의 정보 집합.

 

JMX도 추가. (JMX등 JEE 참고사이트 )


java.util.Concurrent

 - Executor가 대표적: 멀티코어 활용.

   그러나, 일반적인 thread프로그래밍 만으로도 (green thread = single thread OS)가

   아닌 이상은 멀티코어가 어느정도 적용된다고 함.



그 외

http://skycris.tistory.com/3   1.5에 추가된

boxing/unboxing,   - int(원시 형)과  Integer간 자동 형변환.

static import, 

annotation 설명

Posted by yongary
,

nio (jdk1.4)

java core 2015. 1. 16. 15:23

레퍼런스:  http://javacan.tistory.com/tag/nio



속도가 향상된 nio(new io)는 기존 java라기 보단 c코드라고 봐야할 것 같다.


DirectBuffer가 속도가 빠르고, IndirectBuffer는 임시용.

Buffer는 보통 Channel(c언어로 된 Stream이라고 보면 될듯) 과 함께 써야 함.



  ByteBuffer buf = ByteBuffer.allocateDirect(8); 

    buf.putByte( (byte)0xAB );

    buf.putShort( (short)0xCDEF ); 


이렇게 하면, buf에 position=3,  limit=8=capacity 이 됨.

buf.rewind : p=0.

buf.clear() :  p=0, l=8 (초기상태)

buf.flip()    :  p=0, limit=3(현재위치)


뭔가 write한 후에는 남은 byte를 맨 앞으로 옮겨주는

buf.compact() 필요.  주로 buf.isRemaining()과 함께 쓰이는 듯.



<<실제 예제>> 

    FileChannel inputChannel = null;

    FileChannel outputChannel = null;

    try {

        FileIntputStream is = new FileInputStream(source);

        FileOutputStream out = new FileOutputStream(dest);

        inputChannel = is.getChannel();

        outputChannel = out.getChannel();        


    } catch(IOException ex) {



    ByteBuffer buffer = ByteBuffer.allocateDirect(512);

    int len ;

    while ( (len = inputChannel.read(buffer)) != -1) {

         buffer.flip(); //뒤쪽 limit을 마킹. 즉 limit=position,  position=0이 됨


        outputChannel.write(buffer); //읽은거 그대로 write.

        buffer.clear(); //p=0, limit=512가 됨.

    }




<<짧은 파일을  RandomAccess -> MappedByteBuffer (Direct임) 로 매핑해서.. 파일의 내용을 꺼꾸로 하기..>>




            RandomAccessFile ra = new RandomAccessFile("/hello.txt","rw"); 

            FileChannel fc = ra.getChannel(); 

                     

            MappedByteBuffer mbb = fc.map(FileChannel.MapMode.READ_WRITE,0, ra.length()); 


   int len = ra.length();


            RandomAccessFile ra = new RandomAccessFile("/hello.txt","rw"); 

            FileChannel fc = ra.getChannel(); 

                        

            //파일을 파일 채널을 이용하여 버퍼에 매핑 합니다.                        

            MappedByteBuffer mbb = fc.map(FileChannel.MapMode.READ_WRITE,0, ra.length()); 

            

            int len2 = (int)ra.length(); 

            

            //파일 자체 내용을 뒤집기 

            for (int i = 0, j = len2 - 1; i < j; i++, j--) 

            { 

                byte b = mbb.get(i); 

                mbb.put(i, mbb.get(j));  //파일의 내용을 순서 바꿉니다. 

                mbb.put(j, b); 

            } 

                        

            fc.close(); 

Posted by yongary
,

Maven run

Spring 2015. 1. 15. 10:07


pom.xml을 이용해서 직접 run하는 command:



컴파일 + 실행:


    mvn compile exec:java -Dexec.mainClass=com.mongodb.SparkHomework




?아래는 jetty 실행.

mvn clean jetty:run


Posted by yongary
,


/etc/init.d/tomcat7 start
/etc/init.d/tomcat7 stop
/etc/init.d/tomcat7 restart


booting시에 자동으로 시작하는 기능은

$ sudo update-rc.d tomcat(7) defaults


제외는

$ sudo update-rc.d -f tomcat(7) remove

라고 입력합니다.


 

CentOS는 여기 참조: Ref-Site

Posted by yongary
,

hostname 변경

Linux 2014. 11. 14. 17:29

[Redhat계열] Linux hostname변경

$ hostname    : 이건 그냥 조회

$ hostname   abc_server   : 이렇게 세팅가능하며,  리부팅이 되면 원복이 되는 문제점 존재.


리부팅 시에도 적용되게 하려면

/etc/sysconfig/network  여기서 

HOSTNAME=abc_server 이렇게 수정하도록 한다.

Posted by yongary
,

autoFTP.sh

Linux/Linux:sh개발 2014. 10. 29. 11:02

ftp에 접속해서 파일을 다 가져오는 shell script는 다음과 같다.

여기서 EOF 대신에 ENDFILE등 다른 임의의 단어를 사용해도 된다.

 

 

< autoFTP.sh 내용>

 

ftp -n 127.0.0.1 << EOF
user root pass1234
cd ftpserver
prompt off

binary
mget *.out
bye
EOF

Posted by yongary
,

 

흔히 보는 linux의 파일권한 type은 다음과 같다.

-rwsrwsrwt 

 

1. 여기서 현재 '-'로 표시되어 있는
첫 글자가 c/b인 경우라면 device file을 뜻한다. 

(모두 나열하면)
     c:
캐릭터 입출력하는 device

b: 블록 단위로 입출력하는 device
p: named pipe

s: socket
D: door

 

2. 그리고

 네번째, 일곱번째 글자가 s일경우 set-uid 또는 set-gid 비트임.
  
돌리는 동안 잠깐 super (root)가 된다. ps로 확인 가능
    (/
usr/bin/passwd 참고. ) 보안체크시 필수체크항목


3. 마지막 글자가

 

 

  t:sticky  폴더는 타인이 못지우게  /tmp/

 

 

 

 

0. 추가적으로 옵션설정방법:

chmod 에 6777 옵션을 줄 수 있는데

처음 6표시된 자리는

  4: set-uid

  2: set-gid

  1: sticky

과 같은 용도로 사용한다.

Posted by yongary
,

iNode 구조

Linux 2014. 10. 28. 17:34

Linux 및 unix에서는 파일이

 

[File: inode번지] 로 관리가 된다.  (ls i 하면 inode 조회 가능하다) 

 

여기서 inode번지는

è   <inode table 구조>    를 참조하게 된다: (ls –l하면 나오는 정보들이라고 보면 된다)
1File Type
2Permission
3Hard Link Count
(inode 번지 복사) 하드링크시 사용. ( 용법:  ln f1 f2 이며 그 후에 :  rm f1 해도 됨. ) 
                
, 파티션이 다르면 번지중복으로 사용 불가
4Owner
5Group
6Size
7Time
8Point 
à data block저장소를 가르킴
              
symbolic link의 경우 point에 원본위치 있음 (ln -s f1 f2 로 지정)

 Symbolic link
장점: 1. 디렉토리도 된다
                            2.
파티션 달라도 된다.


 

solaris에서는 하드링크를 주로 사용하고

linux에서는 심볼릭 링크(소프트 링크)를 주로 사용하게 된다.

 

 

Posted by yongary
,