@Override protected void compute() { int i = start; int j = end; int swap = -1; while (i < j) { while (i < j && nums[i] <= nums[j]) j--; if (i < j) { swap = nums[i]; nums[i] = nums[j]; nums[j] = swap; } while (i < j && nums[i] < nums[j]) i++; if (i < j) { swap = nums[i]; nums[i] = nums[j]; nums[j] = swap; } } List<ForkJoinTask<Void>> tasks = new LinkedList<>(); if (i - start > 1) { tasks.add(new ForkJoinFastSort(nums, 0, i - 1).fork()); } if (end - j > 1) { tasks.add(new ForkJoinFastSort(nums, j + 1, end).fork()); } for (ForkJoinTask<Void> task : tasks) { task.join(); } }
public static void main(String[] args) { int[] nums = new int[] {5, 4, 6, 2, 8, 7, 9, 1, 3}; ForkJoinPool pool = new ForkJoinPool(); ForkJoinTask<Void> t = pool.submit(new ForkJoinFastSort(nums, 0, 8)); t.join(); for (int i : nums) { System.err.print(i); } }
@Override protected T compute() { List<ForkJoinTask<T>> passes = Lists.newArrayListWithCapacity(nSubOptimizers); for (int i = 0; i < nSubOptimizers; i++) { passes.add(new SingleOptimizationStep(initial, temp).fork()); } T currentBest = initial; double currentBestScore = scorer.score(initial); for (ForkJoinTask<T> pass : passes) { T better = pass.join(); double betterScore = scorer.score(better); if (betterScore > currentBestScore) { currentBest = better; currentBestScore = betterScore; } } return currentBest; }
/** * Wait for all the childPid tasks to complete, and then create the relations * * @throws BackendMethodFailedException * @throws BackendInvalidResourceException * @throws BackendInvalidCredsException */ private void handleNodeEnd() throws BackendMethodFailedException, BackendInvalidResourceException, BackendInvalidCredsException { ArrayList<String> childRealPids = new ArrayList<>(); for (ForkJoinTask<String> childPid : childTasks) { childRealPids.add(childPid.join()); } String comment = "Added relationship from " + myPid + " hasPart to " + childRealPids.size() + " children"; AddRelationsRequest addRelationsRequest = new AddRelationsRequest(); addRelationsRequest.setPid(myPid); addRelationsRequest.setSubject(null); addRelationsRequest.setPredicate(hasPartRelation); addRelationsRequest.setObjects(childRealPids); addRelationsRequest.setComment("Modified by " + getClass().getSimpleName()); UniqueRelationsCreator uniqueRelationsCreator = new UniqueRelationsCreator(fedora); uniqueRelationsCreator.addRelationships(addRelationsRequest); // fedora.addRelations(myPid, null, hasPartRelation, childRealPids, false, comment); log.debug("{}, " + comment, myPid); }
/** * Sorts all the elements of the given array using the ForkJoin framework * * @param array the array to sort */ public void sort(int[] array) { ForkJoinTask<Void> job = pool.submit(new MergeSortTask(array, 0, array.length)); job.join(); }
@Test public void testAsyncRangeRequests() throws IOException, URISyntaxException, InterruptedException { final URL testResourceUrl = new URL(VAULT_BASE_URI.toURL(), "asyncRangeRequestTestFile.txt"); final MultiThreadedHttpConnectionManager cm = new MultiThreadedHttpConnectionManager(); cm.getParams().setDefaultMaxConnectionsPerHost(50); final HttpClient client = new HttpClient(cm); // prepare 8MiB test data: final byte[] plaintextData = new byte[2097152 * Integer.BYTES]; final ByteBuffer bbIn = ByteBuffer.wrap(plaintextData); for (int i = 0; i < 2097152; i++) { bbIn.putInt(i); } // put request: final EntityEnclosingMethod putMethod = new PutMethod(testResourceUrl.toString()); putMethod.setRequestEntity(new ByteArrayRequestEntity(plaintextData)); final int putResponse = client.executeMethod(putMethod); putMethod.releaseConnection(); Assert.assertEquals(201, putResponse); // multiple async range requests: final List<ForkJoinTask<?>> tasks = new ArrayList<>(); final Random generator = new Random(System.currentTimeMillis()); final AtomicBoolean success = new AtomicBoolean(true); // 10 full interrupted requests: for (int i = 0; i < 10; i++) { final ForkJoinTask<?> task = ForkJoinTask.adapt( () -> { try { final HttpMethod getMethod = new GetMethod(testResourceUrl.toString()); final int statusCode = client.executeMethod(getMethod); if (statusCode != 200) { LOG.error("Invalid status code for interrupted full request"); success.set(false); } getMethod.getResponseBodyAsStream().read(); getMethod.getResponseBodyAsStream().close(); getMethod.releaseConnection(); } catch (IOException e) { throw new RuntimeException(e); } }); tasks.add(task); } // 50 crappy interrupted range requests: for (int i = 0; i < 50; i++) { final int lower = generator.nextInt(plaintextData.length); final ForkJoinTask<?> task = ForkJoinTask.adapt( () -> { try { final HttpMethod getMethod = new GetMethod(testResourceUrl.toString()); getMethod.addRequestHeader("Range", "bytes=" + lower + "-"); final int statusCode = client.executeMethod(getMethod); if (statusCode != 206) { LOG.error("Invalid status code for interrupted range request"); success.set(false); } getMethod.getResponseBodyAsStream().read(); getMethod.getResponseBodyAsStream().close(); getMethod.releaseConnection(); } catch (IOException e) { throw new RuntimeException(e); } }); tasks.add(task); } // 50 normal open range requests: for (int i = 0; i < 50; i++) { final int lower = generator.nextInt(plaintextData.length - 512); final int upper = plaintextData.length - 1; final ForkJoinTask<?> task = ForkJoinTask.adapt( () -> { try { final HttpMethod getMethod = new GetMethod(testResourceUrl.toString()); getMethod.addRequestHeader("Range", "bytes=" + lower + "-"); final byte[] expected = Arrays.copyOfRange(plaintextData, lower, upper + 1); final int statusCode = client.executeMethod(getMethod); final byte[] responseBody = new byte[upper - lower + 10]; final int bytesRead = IOUtils.read(getMethod.getResponseBodyAsStream(), responseBody); getMethod.releaseConnection(); if (statusCode != 206) { LOG.error("Invalid status code for open range request"); success.set(false); } else if (upper - lower + 1 != bytesRead) { LOG.error("Invalid response length for open range request"); success.set(false); } else if (!Arrays.equals( expected, Arrays.copyOfRange(responseBody, 0, bytesRead))) { LOG.error("Invalid response body for open range request"); success.set(false); } } catch (IOException e) { throw new RuntimeException(e); } }); tasks.add(task); } // 200 normal closed range requests: for (int i = 0; i < 200; i++) { final int pos1 = generator.nextInt(plaintextData.length - 512); final int pos2 = pos1 + 512; final ForkJoinTask<?> task = ForkJoinTask.adapt( () -> { try { final int lower = Math.min(pos1, pos2); final int upper = Math.max(pos1, pos2); final HttpMethod getMethod = new GetMethod(testResourceUrl.toString()); getMethod.addRequestHeader("Range", "bytes=" + lower + "-" + upper); final byte[] expected = Arrays.copyOfRange(plaintextData, lower, upper + 1); final int statusCode = client.executeMethod(getMethod); final byte[] responseBody = new byte[upper - lower + 1]; final int bytesRead = IOUtils.read(getMethod.getResponseBodyAsStream(), responseBody); getMethod.releaseConnection(); if (statusCode != 206) { LOG.error("Invalid status code for closed range request"); success.set(false); } else if (upper - lower + 1 != bytesRead) { LOG.error("Invalid response length for closed range request"); success.set(false); } else if (!Arrays.equals( expected, Arrays.copyOfRange(responseBody, 0, bytesRead))) { LOG.error("Invalid response body for closed range request"); success.set(false); } } catch (IOException e) { throw new RuntimeException(e); } }); tasks.add(task); } Collections.shuffle(tasks, generator); final ForkJoinPool pool = new ForkJoinPool(4); for (ForkJoinTask<?> task : tasks) { pool.execute(task); } for (ForkJoinTask<?> task : tasks) { task.join(); } pool.shutdown(); cm.shutdown(); Assert.assertTrue(success.get()); }