문제

멀티 코어와 자바에 대한 소란이 많이있는 것 같습니다. 어떤 사람들은 Java 지원이 아니라고 말합니다 충분하다, 그것은 확실히 기대할 지역 인 것 같습니다. 있는 것 같습니다 많은 기법 동시 프로그램의 성능을 향상시킵니다.

다중 코어 시나리오에서 프로그래밍에 대한 팁/조언에 감사드립니다.

도움이 되었습니까?

해결책

새로운 Java 동맹 시설을 살펴보십시오 ( java.util.concurrent 패키지) Java 5에 추가 된)는 일반보다 높은 수준의 기능을 제공합니다. ThreadS는 동시 응용 프로그램을 작성하는 것이 더 쉽고 오류가 적게되기 쉽습니다. 그만큼 수업 : 동시성Java 튜토리얼 시작하기에 좋은 곳이 될 것입니다.

지금까지 나는 만 사용했습니다 ExecutorService,이를 통해 생산할 수 있습니다 스레드 풀, 새로운 작업을 단위로 전달할 수있는 Runnables 또는 Callables (실행 후 값을 반환 할 수 있습니다 Futures) 및 실제 스레딩 코드는 ExecutorService.

예를 들어, 2 스레드의 스레드 풀을 사용하여 계산을 수행하고 결과를 얻는 것은 다음과 같이 간단 할 수 있습니다.

ExecutorService es = Executors.newFixedThreadPool(2);

Future f1 = es.submit(new Callable<Integer>() {
    public Integer call()
    {
        // Do some processing...
        return someInteger;
    }
});

Future f2 = es.submit(new Callable<Integer>() {
    public Integer call()
    {
        // Do some processing...
        return someInteger;
    }
});

Integer firstInteger = f1.get();
Integer secondInteger = f2.get();

위 (테스트되지 않은) 코드에서 걱정해야 할 것은 몇 가지를 만드는 것뿐입니다. Callable모래 submit그것을 ExecutorService 그리고 나중에, Future결과를 검색합니다.

캐치는 일단입니다 get 방법의 방법 Future 처리가 완료되지 않으면 프로그램은 결과가 발생할 때까지 중지됩니다. Future 검색 할 수 있습니다. 따라서이 예에서는 결과가 f2 전에 사용할 수 있습니다 f1, 프로그램은 결과가 될 때까지 기다립니다 f1 사용할 수 있습니다.

독서 자료의 관점에서, 곧 구매할 책 목록에서 실제로 Java 동시성 Brian Goetz, Java의 동시성이 자라면 자주 나타납니다.

그만큼 동시 유틸리티 Java 5 문서의 페이지에는 더 많은 정보가 있습니다.

다른 팁

가장 좋은 팁은 다음과 같습니다. 동기화를 올바르게 얻으십시오!

이것은 다소 명백해 보이지만 자바 메모리 모델 특히 어떻게 중요합니다 휘발성 물질 그리고 결정적인 필드는 작동합니다 동기화 뮤텍스로 작용합니다 그리고메모리 장벽 그리고 새로운 java.util.concurrent 구성도 구성됩니다

항상 좋은 팁 - 불변성이 불변성이 많은 우려 장소로의 자물쇠에 대해 걱정할 필요가 없기 때문에 대부분의 수업이 불변이되면 모든 것이 훨씬 쉬워집니다.

다가오는 것을 확인하십시오 포크 조인 프레임 워크. Fork-Join 프레임 워크를 통해 개발자는 멀티 코어 아키텍처에서 세밀한 병렬 처리를 달성 할 수 있습니다.

또한 JVM 기반 언어를 확인하고 싶을 수도 있습니다. Clojure 그것은 멀티 코어 병렬 프로그래밍을 더 쉽게 만들어 낸다고 주장합니다.

동시성에 대한 Java 자신의 공유 메모리 접근 방식에 대한 대안으로 스칼라를 사용한 액터 기반 동시성 Java 위에는 동시 프로그래밍을위한 더 쉬운 모델을 제공합니다.

Brian Goetz의 대화를 확인하십시오 동시에서 평행까지 Devoxx 2008에서. 팁이 많지는 않지만 Java Concurrency가 어디로 향하고 있는지 아이디어를 제공합니다.

You can try to use a parallelism patterns library such as Skandium for Java. Simply choose the parallelism pattern you want and fill in the missing hooks.

Some of the patterns sopported in Skandium are:

  • Master-slave: Farm<P,R>(nested);
  • Pipeline: `Pipe(stage1, stage2);
  • For iteration: For<P,R>(nested, i);
  • Conditional iteration: While<P,R>(nested, condition);
  • Conditional branching: If<P,R>(condition, trueCase, falseCase);
  • Map-reduce: Map<P,R>(split, nested, merge);
  • Map-reduce with different code paths: Fork<P,R>(split, nested, merge);
  • Recursive divide and conquer: DaC<P,R>(condition, split, nested, merge);

All patterns can be nested and combine, so you can have farm inside of a divide and conquer, etc.

The best book with practical tips has been Java Concurrency in Practise. It is a must read for all java programmers, even those who thinks they dont do any concurrent programming, because java has many hidden threading in its various libraries (swing comes to mind, same with servlets).

My tip: Understand the Java Memory Model (since JDK 5 and higher). Most people do not know, that synchronization, volatile, and final have an additional meaning beyond the normal multi-threading scope.

Java is fine for multi-cpu and multi-cores. If you program it right and you invest some brain, you get a highly concurrent server system to utilize 8-cores including a lot of synchronization and so on. We are quite happy with it... JDK6 is better than JDK5 and everything below sucks on multi-cpu machines.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top