001 /* 002 * Copyright (C) 2008-2010 by Holger Arndt 003 * 004 * This file is part of the Universal Java Matrix Package (UJMP). 005 * See the NOTICE file distributed with this work for additional 006 * information regarding copyright ownership and licensing. 007 * 008 * UJMP is free software; you can redistribute it and/or modify 009 * it under the terms of the GNU Lesser General Public License as 010 * published by the Free Software Foundation; either version 2 011 * of the License, or (at your option) any later version. 012 * 013 * UJMP is distributed in the hope that it will be useful, 014 * but WITHOUT ANY WARRANTY; without even the implied warranty of 015 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 016 * GNU Lesser General Public License for more details. 017 * 018 * You should have received a copy of the GNU Lesser General Public 019 * License along with UJMP; if not, write to the 020 * Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, 021 * Boston, MA 02110-1301 USA 022 */ 023 024 package org.ujmp.core.util.concurrent; 025 026 import java.util.concurrent.Callable; 027 import java.util.concurrent.Future; 028 import java.util.concurrent.ThreadPoolExecutor; 029 030 import org.ujmp.core.util.UJMPSettings; 031 032 public abstract class PFor { 033 034 private final Object[] objects; 035 036 public PFor(final int threads, final int first, final int last, final Object... objects) { 037 this.objects = objects; 038 039 if (threads < 2) { 040 for (int i = first; i <= last; i++) { 041 step(i); 042 } 043 } else { 044 final ThreadPoolExecutor es = UJMPThreadPoolExecutor.getInstance(threads); 045 046 final Future<?>[] list = new Future[threads]; 047 final double stepsize = (double) (last + 1 - first) / threads; 048 049 for (int i = 0; i < threads; i++) { 050 int starti = (int) Math.ceil(first + i * stepsize); 051 int endi = (int) Math.ceil(first + (i + 1) * stepsize); 052 list[i] = es.submit(new StepCallable(starti, endi)); 053 } 054 055 for (Future<?> f : list) { 056 try { 057 f.get(); 058 } catch (Exception e) { 059 e.printStackTrace(); 060 } 061 } 062 } 063 } 064 065 public PFor(final int first, final int last, final Object... objects) { 066 this(UJMPSettings.getNumberOfThreads(), first, last, objects); 067 } 068 069 public abstract void step(final int i); 070 071 public final Object getObject(final int i) { 072 return objects[i]; 073 } 074 075 class StepCallable implements Callable<Object> { 076 private final int first; 077 private final int last; 078 079 public StepCallable(final int first, final int last) { 080 this.first = first; 081 this.last = last; 082 } 083 084 public final Void call() throws Exception { 085 try { 086 for (int i = first; i < last; i++) { 087 step(i); 088 } 089 } catch (Exception e) { 090 e.printStackTrace(); 091 } 092 return null; 093 } 094 095 } 096 097 }