기본 콘텐츠로 건너뛰기

BaseStream

Stream 인터페이스는 BaseStream을 상속받는다.
Stream을 보기전에 미리 BaseStream을 볼 필요가 있다. 
public interface Stream<T> extends BaseStream<T, Stream<T>> {
...
BaseStream은 AutoCloseable인터페이스를 상속받고 다음과 같은 몇가지의 함수들을 가지고 있다.
public interface BaseStream<T, S extends BaseStream<T, S>>  
        extends AutoCloseable {
        
Iterator<T> iterator();
spliterator<T> spliterator();
boolean isParallel();
S sequential();
S parallel();
S unordered();
S onClose(Runnable closeHandler);
@Override
void close();

}
자바8 이후에서 인터페이스는 함수를 선언으로만 끝내지 않고 정의까지 포함한다. 그 대표적인 예가 람다식을 사용하는 @FunctionalInterface( https://docs.oracle.com/javase/8/docs/api/java/lang/FunctionalInterface.html) 이다. 하지만 BaseStream은 선언부만 정의되어있다. 즉 상속받는곳에서 입맛에 맛게 오버라이드 하여 사용하고 있다.
/**  
 * Returns an iterator for the elements of this stream. * * <p>This is a <a href="package-summary.html#StreamOps">terminal  
 * operation</a>.  
 * * @return the element iterator for this stream  
 */
Iterator<T> iterator();
Stream의 엘리먼트들을 접근할 수 있는 Iterator를 반환해준다.
IntStream ins1 = IntStream.range(0, 10);  
Iterator<Integer> it1 = ins1.iterator();  
 
int sum0 = 0;  
while(it1.hasNext()){  
   sum0 += it1.next();  
}  
System.out.println(sum0); -> 45
Stream을 일반적으로 사용하는 Iterator와 동일하게 사용할 수 있다.
/**  
 * Returns a spliterator for the elements of this stream. * * <p>This is a <a href="package-summary.html#StreamOps">terminal  
 * operation</a>.  
 * * @return the element spliterator for this stream  
 */
Spliterator<T> spliterator();  
주석만 읽어보면 Iterator와 다를것 없어보이지만 Spliterator에 대해 알필요가 있다. 자바8에서 생겨난 인터페이스며 기존의 Iterator와는 다른 역할을 한다. spliterator 는 처리할 작업을 분할해서 수행할때 사용한다. 병렬처리할때 유용하다.
/**  
 * Returns whether this stream, if a terminal operation were to be executed, * would execute in parallel.  Calling this method after invoking an * terminal stream operation method may yield unpredictable results. * * @return {@code true} if this stream would execute in parallel if executed  
 */
 boolean isParallel();  
이 스트림의 터미널 오퍼레이션, 즉 마지막에 실행되는 종료함수를 병렬로 처리할지 여부를 반환해준다.
/**  
 * Returns an equivalent stream that is sequential.  May return * itself, either because the stream was already sequential, or because * the underlying stream state was modified to be sequential. * * <p>This is an <a href="package-summary.html#StreamOps">intermediate  
 * operation</a>.  
 * * @return a sequential stream  
 */
 S sequential();  
만약 stream이 병렬로 설정되어있다면 이를 해제하여 stream을 다시 돌려준다.
/**  
* Returns an equivalent stream that is parallel.  May return * itself, either because the stream was already parallel, or because * the underlying stream state was modified to be parallel. * * <p>This is an <a href="package-summary.html#StreamOps">intermediate  
* operation</a>.  
* * @return a parallel stream  
*/
S parallel();  
sequential()과 반대로 해당 stream이 병렬로 설정되어있지 않다면 병렬로 설정하여 stream을 돌려준다.
/**  
* Returns an equivalent stream that is * <a href="package-summary.html#Ordering">unordered</a>.  May return  
* itself, either because the stream was already unordered, or because * the underlying stream state was modified to be unordered. * * <p>This is an <a href="package-summary.html#StreamOps">intermediate  
* operation</a>.  
* * @return an unordered stream  
*/
S unordered();  
스트림의 구성요소들의 순서를 해제하는 기능이다. array나 list는 순서가 있다. 하지만 hashset는 순서가 없다. stream에서는 병렬처리를 진행할 경때 순서가 없는 상태인경우 더 나은 성능을 보여준다.
/**  
* Returns an equivalent stream with an additional close handler.  Close * handlers are run when the {@link #close()} method  
* is called on the stream, and are executed in the order they were * added.  All close handlers are run, even if earlier close handlers throw * exceptions.  If any close handler throws an exception, the first * exception thrown will be relayed to the caller of {@code close()}, with  
* any remaining exceptions added to that exception as suppressed exceptions * (unless one of the remaining exceptions is the same exception as the * first exception, since an exception cannot suppress itself.)  May * return itself. * * <p>This is an <a href="package-summary.html#StreamOps">intermediate  
* operation</a>.  
* * @param closeHandler A task to execute when the stream is closed  
* @return a stream with a handler that is run if the stream is closed  
*/
S onClose(Runnable closeHandler);  
스트림에 파라미터로 전달받은 closeHandler를 추가해주는 기능이다.
/**  
* Closes this stream, causing all close handlers for this stream pipeline * to be called. * * @see AutoCloseable#close()  
*/@Override  
void close();
stream을 종료하는 함수이다.

댓글

이 블로그의 인기 게시물

메일서버가 스팸으로 취급받을때

설치한 메일서버를 통해 발송되는 메일이 스팸으로 들어가는 경우가 더러 있다. 이게 한번 들어가기는 쉬운데, 빠져나오기는 드럽게 힘든것 같다... 본인의 경우에는 우선 국내서비스에는 별 무리 없이 들어간다. (naver,daum 등) 그런데 해외메일 그중 Gmail, Hotmail 에는 에누리없이 스팸으로 간주되고 있었다. Gmail같은 경우에는 그래도 스팸함으로 발송은 제대로 되는반면에 Hotmail같은경우에는 아예 수신자체가 안되는 경우도 더러있다.. ㅡ,.ㅡ; 제일 좋은 방법은 Gmail,Hotmail에 전화걸어서 우리 메일서버 IP white Ip로 등록해달라!!! 하면 좋지만, 얘네들은 걸어봤자 자동응답기고, 문의채널은 구글 그룹스 게시판이 전부다.. 본론으로 들어가서. 해외 메일이 차단될 경우 내 매일서버ip가 스팸ip로 등록되 버린 경우일 수 있다. (본인처럼. ㅎ) 이것부터 조회 해보고 싶으면 RBL(real-time blocking List) 체크를 해야 하는데, RBL체크 해주는 사이트는 꽤 많이 있고, 그중 좀 깔끔해 보이는곳 하나 소개. http://www.anti-abuse.org/ 메일서버ip 입력하고 조회해보면 쭈루룩 리스트가 나온다. 그 중 빨간불이 들어온 부분이 메일 서버가 스팸서버가 된 각종 이유들이다.ㅋ 본인의 경우 CBL 때문에 걸렸는데, 내용은 아래와 같다. This IP address is HELO'ing as  "localhost.localdomain"  which violates the relevant standards (specifically: RFC5321). 메일서버 도메인에 별다른 작업을 안해놓아서 "localhost.localdomain" 으로 설정되어있었다. 만약 CBL만 바로 테스트 해보고 싶으면 http://cbl.abusea

[javascript] 특정시간에만 함수 실행

특정시간에만 팝업을 띄우려면?? 특정시간에만 로그인을 막으려면?? 특정시간에만 할일은 의외로 참 많다. 방법? 딱히 없다. 현재시간 구해서 시작시간, 종료시간 사이에 있을때 시작하는 수밖엔. if ((현재시간 > 시작시간) && (현재시간 < 종료시간)){ .. 팝업노출(); 공사페이지 리다이렉트(); 기타등등(); .. } 자바스크립트로 작성하면 다음과 같다. var startdate = "2014012008" ; var enddate = "2014012418" ; var now = new Date (); //현재시간 year = now. getFullYear (); //현재시간 중 4자리 연도 month = now. getMonth () + 1 ; //현재시간 중 달. 달은 0부터 시작하기 때문에 +1 if ((month + "" ). length < 2 ){ month = "0" + month; //달의 숫자가 1자리면 앞에 0을 붙임. } date = now. getDate (); //현재 시간 중 날짜. if ((date + "" ). length < 2 ){ date = "0" + date; } hour = now. getHours (); //현재 시간 중 시간. if ((hour + "" ). length < 2 ){ hour = "0" + hour; } today = year + "" + month + "" + date + "" + hour; //오늘 날짜 완성. / / 시간비교 i

스레드 동기화1 - syncronized

구현 스레드를 구현하는 방법은 2가지다. 1. Thread 클래스를 extends 한다. 2. Runnable 인터페이스를 implements 한다. 뭐 사실 Thread는 생성자의 변수로 Runnable을 취한다. public Thread (Runnable target) { init( null, target , "Thread-" + nextThreadNum () , 0 ) ; } 그리고 Runnable 인터페이스는 run() 이라는 단일함수를 갖는 인터페이스이다. @FunctionalInterface public interface Runnable { /** * When an object implementing interface <code> Runnable </code> is used * to create a thread, starting the thread causes the object's * <code> run </code> method to be called in that separately executing * thread. * <p> * The general contract of the method <code> run </code> is that it may * take any action whatsoever. * * @see java.lang.Thread#run() */ public abstract void run () ; } 그렇기 때문에 람다식으로 표현이 가능한 것이다. 동기화 동기화는 동시에 같은자원의 접근을 제한하고자 할때 사용한다. 예를들어, 한 우물에서 물을 15번 길어야 하는 일을 해야할때 5명이서 3번만 하면 수고를 5배로 줄일수 있다. 그런데 우물은 하난데 동시에