示例#1
0
  public T doWork(T context, int niters, Result<T> opts) {

    opts.setErrorCount(0);

    ActionRecord record = new ActionRecord();
    ActionRecord logRecord = new ActionRecord();

    final int transactionSize =
        ThreadLocalRandom.current().nextInt(this.maxTransactionSize) + this.minTransactionSize;
    List<String> keysToUse = keys.getRandomKeyList(transactionSize, true);

    // If this is a logger
    if (writeToLogs > 0 && ThreadLocalRandom.current().nextInt(1000) < 1) {
      System.out.println("Log Reader");

      record = machine.readLog(3, millisBetweenActions);
      workTimeMillis = System.currentTimeMillis();
      return null;
    }

    if (keysToUse.size() < 2) {
      System.out.println("whoa there...");
    }

    // Get Random number to assign task
    final int rand1 = ThreadLocalRandom.current().nextInt(1000);
    if (rand1 < chanceOfRead) {
      // Reader
      record = machine.read(keysToUse, millisBetweenActions);
    } else if (rand1 < chanceOfWrite) {
      // Writer
      record = machine.update(keysToUse, millisBetweenActions);
    } else if (rand1 < chanceOfReadModifyWrite) {
      // Reader + Writer
      record = machine.readModifyWrite(keysToUse, millisBetweenActions);
    } else if (rand1 < chanceOfBalanceTransfer) {
      record = machine.balanceTransfer(keysToUse.get(0), keysToUse.get(1), millisBetweenActions);
    } else if (rand1 < chanceOfIncrementalUpdate) {
      record = machine.incrementalUpdate(keysToUse, millisBetweenActions);
    }

    // Write the logs (if there are any to write)
    if (writeToLogs > 0) logRecord = machine.writeLog(writeToLogs, millisBetweenActions);

    // Check for success
    if (record == null
        || !record.isSuccess()
        || (writeToLogs > 0 && (logRecord == null || !logRecord.isSuccess()))) {

      opts.incrementErrorCount();
    }

    workTimeMillis = System.currentTimeMillis();

    return null;
  }
  public static void IA() {
    while (true) {
      if (!(remplis(TabManager.horizontale))) {
        System.out.println("IA H");

        int cooxH = ThreadLocalRandom.current().nextInt(0, l);
        int cooyH = ThreadLocalRandom.current().nextInt(0, c - 1);

        while (TabManager.horizontale[cooxH][cooyH] == 1) {
          cooxH = ThreadLocalRandom.current().nextInt(0, l);
          cooyH = ThreadLocalRandom.current().nextInt(0, c - 1);
        }
        TabManager.horizontale[cooxH][cooyH] = 1;
        Test1.b = true;
        break;
      }

      if (!(remplis(TabManager.verticale))) {
        System.out.println("IA V");
        int cooxV = ThreadLocalRandom.current().nextInt(0, l - 1);
        int cooyV = ThreadLocalRandom.current().nextInt(0, c);

        while (TabManager.verticale[cooxV][cooyV] == 1) {
          cooxV = ThreadLocalRandom.current().nextInt(0, l - 1);
          cooyV = ThreadLocalRandom.current().nextInt(0, c);
        }
        TabManager.verticale[cooxV][cooyV] = 1;
        Test1.b = true;
        break;
      }
    }
  }
示例#3
0
  public PoolBagEntry(final Connection connection, final HikariPool pool) {
    this.connection = connection;
    this.parentPool = pool;
    this.creationTime = System.currentTimeMillis();
    this.poolElf = pool.poolElf;
    this.state = new AtomicInteger(STATE_NOT_IN_USE);
    this.lastAccess = ClockSource.INSTANCE.currentTime();
    this.openStatements = new FastList<>(Statement.class, 16);

    poolElf.resetPoolEntry(this);

    final long maxLifetime = pool.config.getMaxLifetime();
    final long variance = maxLifetime > 60_000 ? ThreadLocalRandom.current().nextLong(10_000) : 0;
    final long lifetime = maxLifetime - variance;
    if (lifetime > 0) {
      endOfLife =
          pool.houseKeepingExecutorService.schedule(
              new Runnable() {
                @Override
                public void run() {
                  // If we can reserve it, close it
                  if (pool.connectionBag.reserve(PoolBagEntry.this)) {
                    pool.closeConnection(PoolBagEntry.this, "(connection reached maxLifetime)");
                  } else {
                    // else the connection is "in-use" and we mark it for eviction by
                    // pool.releaseConnection() or the housekeeper
                    PoolBagEntry.this.evicted = true;
                  }
                }
              },
              lifetime,
              TimeUnit.MILLISECONDS);
    }
  }
 @Test
 public void testRandomRangeAndBatches() throws ExecutionException, InterruptedException {
   ThreadLocalRandom random = ThreadLocalRandom.current();
   int treeSize = random.nextInt(maxTreeSize / 10, maxTreeSize * 10);
   for (int i = 0; i < perThreadTrees / 10; i++)
     testInsertions(threads * 10, treeSize, random.nextInt(1, 100) / 10f, treeSize / 100, true);
 }
 /** Store data to StorageNode with the Node is selected randomly */
 public void bindReplicasToStorageNodeRand_Net() {
   int replicaNum = replicaList.size();
   int nodeSize = nodeList.size();
   for (int i = 0; i < replicaNum; i++) {
     BlockReplica replica = replicaList.get(i);
     StorageNode node =
         nodeList.get(java.util.concurrent.ThreadLocalRandom.current().nextInt(nodeSize));
     double replicaSize = replica.getSize();
     if (node.getAvailableSpace() - replicaSize >= 0.000000000000000000000001
         && !node.contains(replica.getName())) {
       double time = node.addFile(replica);
       double accrossLatency = NetworkTopology.getDelay(getId(), node.getDatacenter().getId());
       time += accrossLatency;
       /*Log.printLine("it take " + time
       + " seconds to write the replica #" + replica.getId()
       + " to be stored in datacenter "
       + node.getDatacenter().getName() + " node #"
       + node.getId());*/
       Log.printLine(
           "replica #"
               + replica.getId()
               + "    			"
               + node.getDatacenter().getName()
               + " node #"
               + node.getId()
               + " 			"
               + time);
     } else {
       i--;
     }
   }
 }
  /** @throws Exception If failed. */
  public void testConcurrentStart() throws Exception {
    ThreadLocalRandom rnd = ThreadLocalRandom.current();

    for (int i = 0; i < 3; i++) {
      try {
        clientNodes = new HashSet<>();

        while (clientNodes.size() < 2) clientNodes.add(rnd.nextInt(1, NODES_CNT));

        clientNodes.add(NODES_CNT - 1);

        log.info("Test iteration [iter=" + i + ", clients=" + clientNodes + ']');

        Ignite srv = startGrid(0); // Start server node first.

        assertFalse(srv.configuration().isClientMode());

        startGridsMultiThreaded(1, NODES_CNT - 1);

        checkTopology(NODES_CNT);

        awaitPartitionMapExchange();

        for (int node : clientNodes) {
          Ignite ignite = grid(node);

          assertTrue(ignite.configuration().isClientMode());
        }
      } finally {
        stopAllGrids();
      }
    }
  }
public class DutchNationalFlagTest {
  private ThreadLocalRandom random = ThreadLocalRandom.current();

  @Rule public MockitoRule mrule = MockitoJUnit.rule();

  private int[] createRandomItems(int size) {
    return IntStream.range(0, size).mapToObj(i -> random.nextInt(3)).mapToInt(i -> i).toArray();
  }

  @Test
  public void sort() throws Exception {
    int size = 100;
    int[] items = createRandomItems(size);
    DutchNationalFlag service = spy(new DutchNationalFlag(items));
    service.sort();
    int i = 0;
    while (i < size && items[i++] == 0) ;
    assertTrue(items[i] == 1);
    while (i < size && items[i++] == 1) ;
    assertTrue(items[i] == 2);
    while (i < size && items[i++] == 2) ;
    assertEquals(i, size);
    verify(service, atMost(size)).getColor(anyInt());
    verify(service, atMost(size)).swap(anyInt(), anyInt());
  }
}
示例#8
0
  public static void timeLookup(TreeSet<Integer> tree, long size) {
    tree.contains(7);
    tree.contains(4038);
    tree.contains(2898833);

    int limit = 50000000;
    int randomSize = 1000000;

    // Generate a list of random numbers to get rid of the time it takes
    // to generate the numbers
    ArrayList<Integer> randomNums = new ArrayList<>();
    for (int i = 0; i < randomSize; i++)
      randomNums.add(ThreadLocalRandom.current().nextInt(0, (int) size));

    // Store the overhead of a for loop
    long start = System.nanoTime();
    for (int i = 0; i < limit; i++) ;
    long stop = System.nanoTime();
    long overheadTime = stop - start;

    // Time the lookups
    start = System.nanoTime();
    for (int i = 0; i < limit; i++) tree.contains(randomNums.get(i % randomSize));
    stop = System.nanoTime();

    System.out.println((stop - start - overheadTime) / 1000000);
  }
示例#9
0
 protected int generateRandomIndex() {
   if (tickets.size() == 1) {
     return 0;
   }
   int index = ThreadLocalRandom.current().nextInt(1, tickets.size());
   return index;
 }
 @Override
 public MutatedInstanceMetaData<MultiMaskEfsmSkeleton, MultiMaskEfsmMutation> apply(
     MultiMaskEfsmSkeleton individual) {
   List<Step> transitions = getTransitions(individual);
   if (transitions.isEmpty()) {
     return new MutatedInstanceMetaData<MultiMaskEfsmSkeleton, MultiMaskEfsmMutation>(
         new MultiMaskEfsmSkeleton(individual), new MutationCollection<MultiMaskEfsmMutation>());
   }
   MyMap num = new MyMap();
   for (Step s : transitions) {
     num.put(s, 1);
   }
   for (VarsActionsScenario s : individual.getCounterExamples()) {
     getTrace(individual, s, num);
   }
   double sum = 0;
   for (Step s : transitions) {
     sum += num.get(s);
   }
   int i = 0;
   double cur = num.get(transitions.get(0)) / sum;
   ThreadLocalRandom random = ThreadLocalRandom.current();
   while (random.nextDouble() > cur) {
     i++;
     cur += num.get(transitions.get(i)) / sum;
   }
   Step s = transitions.get(i);
   MultiMaskEfsmSkeleton ind = new MultiMaskEfsmSkeleton(individual);
   int x = random.nextInt(MultiMaskEfsmSkeleton.STATE_COUNT);
   ind.getState(s.state).getTransitionGroup(s.event, s.group).setNewState(s.index, x);
   return new MutatedInstanceMetaData<MultiMaskEfsmSkeleton, MultiMaskEfsmMutation>(
       ind,
       new MutationCollection<MultiMaskEfsmMutation>(
           new DestinationStateMutation(s.state, s.event, s.group, s.index, x)));
 }
示例#11
0
 private void generaCodice() {
   Object[] colori = ColoriDisponibili.disponibili.getColori().keySet().toArray();
   for (int i = 0; i < 4; i++) {
     int indice = ThreadLocalRandom.current().nextInt(0, colori.length);
     codice.aggiungiNumero((Color) colori[indice]);
   }
 }
示例#12
0
 @Test
 @Ignore(
     "Very simple microbenchmark to compare different writeTo implementations. Only for development thus "
         + "ignored.")
 public void testWriteToMicrobenchmark() throws IOException {
   int capacity = 1024 * 128;
   int iterations = 100;
   int testRuns = 10;
   byte[] bytes = new byte[capacity];
   ThreadLocalRandom.current().nextBytes(bytes);
   ByteBuffer buffer = BufferUtil.allocate(capacity);
   BufferUtil.append(buffer, bytes, 0, capacity);
   long startTest = System.nanoTime();
   for (int i = 0; i < testRuns; i++) {
     long start = System.nanoTime();
     for (int j = 0; j < iterations; j++) {
       ByteArrayOutputStream out = new ByteArrayOutputStream();
       long startRun = System.nanoTime();
       BufferUtil.writeTo(buffer.asReadOnlyBuffer(), out);
       long elapsedRun = System.nanoTime() - startRun;
       //                LOG.warn("run elapsed={}ms", elapsedRun / 1000);
       assertThat(
           "Bytes in out equal bytes in buffer",
           Arrays.equals(bytes, out.toByteArray()),
           is(true));
     }
     long elapsed = System.nanoTime() - start;
     LOG.warn("elapsed={}ms average={}ms", elapsed / 1000, elapsed / iterations / 1000);
   }
   LOG.warn(
       "overall average: {}ms", (System.nanoTime() - startTest) / testRuns / iterations / 1000);
 }
  @Test
  public void testManyClusterings() throws Throwable {
    StringBuilder table = new StringBuilder("CREATE TABLE %s (a TEXT");
    StringBuilder cols = new StringBuilder();
    StringBuilder args = new StringBuilder("?");
    List<Object> vals = new ArrayList<>();
    vals.add("a");
    for (int i = 0; i < 40; i++) {
      table.append(", c").append(i).append(" text");
      cols.append(", c").append(i);
      if (ThreadLocalRandom.current().nextBoolean()) vals.add(Integer.toString(i));
      else vals.add("");
      args.append(",?");
    }
    args.append(",?");
    vals.add("value");
    table.append(", v text, PRIMARY KEY ((a)").append(cols).append("))");
    createTable(table.toString());

    execute("INSERT INTO %s (a" + cols + ", v) VALUES (" + args + ")", vals.toArray());
    flush();
    UntypedResultSet.Row row = execute("SELECT * FROM %s").one();
    for (int i = 0; i < row.getColumns().size(); i++)
      Assert.assertEquals(vals.get(i), row.getString(i == 0 ? "a" : i < 41 ? "c" + (i - 1) : "v"));
  }
  /** @throws Exception If failed. */
  public void testLockSerialization() throws Exception {
    final IgniteLock lock = grid(0).reentrantLock("lock", true, true, true);

    info("Lock created: " + lock);

    lock.isFailoverSafe();
    lock.isFair();

    grid(ThreadLocalRandom.current().nextInt(G.allGrids().size()))
        .compute()
        .broadcast(
            new IgniteCallable<Object>() {
              @Nullable
              @Override
              public Object call() throws Exception {
                Thread.sleep(1000);

                lock.lock();

                try {
                  info("Inside lock: " + lock.getHoldCount());
                } finally {
                  lock.unlock();
                }

                return null;
              }
            });
  }
  public Observable<List<TwitterUser>> searchUsers(String prefix) {
    if (ThreadLocalRandom.current().nextDouble() < failureProbability) {
      return Observable.error(new IOException("Broken pipe"));
    }

    return Observable.from(users).skip(1).toList().subscribeOn(Schedulers.newThread());
  }
 // select a random subset of the keys, with an optional random population of keys inbetween those
 // that are present
 // return a value with the search position
 private static List<Integer> randomKeys(
     Iterable<Integer> canonical, boolean mixInNotPresentItems) {
   ThreadLocalRandom rnd = ThreadLocalRandom.current();
   boolean useFake = mixInNotPresentItems && rnd.nextBoolean();
   final float fakeRatio = rnd.nextFloat();
   List<Integer> results = new ArrayList<>();
   Long fakeLb = null, fakeUb = null;
   for (Integer v : canonical) {
     if (!useFake
         || fakeLb == null
         || (fakeUb == null ? v - 1 : fakeUb) <= fakeLb + 1
         || rnd.nextFloat() < fakeRatio) {
       // if we cannot safely construct a fake value, or our randomizer says not to, we emit the
       // next real value
       results.add(v);
       fakeLb = v.longValue();
       fakeUb = null;
     } else {
       // otherwise we emit a fake value in the range immediately proceeding the last real value,
       // and not
       // exceeding the real value that would have proceeded (ignoring any other suppressed real
       // values since)
       if (fakeUb == null) fakeUb = v.longValue() - 1;
       long mid = (fakeLb + fakeUb) / 2;
       assert mid < fakeUb;
       results.add((int) mid);
       fakeLb = mid;
     }
   }
   final float useChance = rnd.nextFloat();
   return Lists.newArrayList(filter(results, (x) -> rnd.nextFloat() < useChance));
 }
示例#17
0
  public static String generateHallmark(String secretPhrase, String host, int weight, int date) {

    if (host.length() == 0 || host.length() > 100) {
      throw new IllegalArgumentException("Hostname length should be between 1 and 100");
    }
    if (weight <= 0 || weight > Constants.MAX_BALANCE_NXT) {
      throw new IllegalArgumentException(
          "Weight should be between 1 and " + Constants.MAX_BALANCE_NXT);
    }

    byte[] publicKey = Crypto.getPublicKey(secretPhrase);
    byte[] hostBytes = Convert.toBytes(host);

    ByteBuffer buffer = ByteBuffer.allocate(32 + 2 + hostBytes.length + 4 + 4 + 1);
    buffer.order(ByteOrder.LITTLE_ENDIAN);
    buffer.put(publicKey);
    buffer.putShort((short) hostBytes.length);
    buffer.put(hostBytes);
    buffer.putInt(weight);
    buffer.putInt(date);

    byte[] data = buffer.array();
    data[data.length - 1] = (byte) ThreadLocalRandom.current().nextInt();
    byte[] signature = Crypto.sign(data, secretPhrase);

    return Convert.toHexString(data) + Convert.toHexString(signature);
  }
  @Override
  public List<FSM> apply(List<FSM> parents) {
    int numberOfStates = parents.get(0).getNumberOfStates();
    int numberOfEvents = parents.get(0).getNumberOfEvents();
    List<String> events = parents.get(0).getEvents();

    int point = ThreadLocalRandom.current().nextInt(parents.get(0).getNumberOfStates());
    FSM.Transition[][] tr0 = new FSM.Transition[numberOfStates][numberOfEvents];
    FSM.Transition[][] tr1 = new FSM.Transition[numberOfStates][numberOfEvents];

    for (int state = 0; state < numberOfStates; state++) {
      if (state < point) {
        tr0[state] =
            Arrays.copyOf(
                parents.get(0).transitions[state], parents.get(0).transitions[state].length);
        tr1[state] =
            Arrays.copyOf(
                parents.get(1).transitions[state], parents.get(1).transitions[state].length);
      } else {
        tr0[state] =
            Arrays.copyOf(
                parents.get(1).transitions[state], parents.get(1).transitions[state].length);
        tr1[state] =
            Arrays.copyOf(
                parents.get(0).transitions[state], parents.get(0).transitions[state].length);
      }
    }

    List<FSM> offspring = new ArrayList<FSM>();
    offspring.add(new FSM(numberOfStates, tr0));
    offspring.add(new FSM(numberOfStates, tr1));
    return offspring;
  }
示例#19
0
 /**
  * 产生len个[min,max)随机数(jdk7)
  *
  * @param min
  * @param max
  * @param len
  * @return
  */
 public static int[] generateRandomArrayWithJava7(int min, int max, int len) {
   int[] randomArray = new int[len];
   for (int i = 0; i < len; i++) {
     randomArray[i] = ThreadLocalRandom.current().nextInt(min, max);
   }
   return randomArray;
 }
示例#20
0
  @Override
  public CharSequence process(final Message message) throws MessageProcessingException {

    if (!enabled) {
      return null;
    }

    final Matcher m = COMMAND_PATTERN.matcher(message.getBody());
    if (!m.matches()) {
      return null;
    }

    final String userNick = MessageProcessorUtils.getUserNick(message);

    final String dcString = m.group(1);
    final String dsString = m.group(2);
    if (dcString.length() > 4 || dsString.length() > 5) {
      return userNick + ": я не настолько умная же! >_<\"";
    }

    final int diceCount = Integer.parseInt(dcString);
    final int dieSides = Integer.parseInt(dsString);
    final Random random = ThreadLocalRandom.current();
    int result = 0;
    for (int i = 0; i < diceCount; i++) {
      result += random.nextInt(dieSides) + 1;
    }
    return userNick + ": Выпало " + result + ", такие дела, нян!";
  }
  /** ************************ TEST ACCESS ******************************************* */
  @Test
  public void testSearchIterator() throws InterruptedException {
    final int perTreeSelections = 100;
    testRandomSelection(
        perThreadTrees,
        perTreeSelections,
        (test) -> {
          IndexedSearchIterator<Integer, Integer> iter1 = test.testAsSet.iterator();
          IndexedSearchIterator<Integer, Integer> iter2 = test.testAsList.iterator();
          return (key) -> {
            Integer found1 = iter1.hasNext() ? iter1.next(key) : null;
            Integer found2 = iter2.hasNext() ? iter2.next(key) : null;
            Assert.assertSame(found1, found2);
            if (found1 != null) Assert.assertEquals(iter1.indexOfCurrent(), iter2.indexOfCurrent());

            int index = Collections.binarySearch(test.canonicalList, key, test.comparator);
            if (index < 0) {
              Assert.assertNull(found1);
            } else {
              Assert.assertEquals(key, found1);
              Assert.assertEquals(index, iter1.indexOfCurrent());
            }

            // check that by advancing the same key again we get null, but only do it on one of the
            // two iterators
            // to ensure they both advance differently
            if (ThreadLocalRandom.current().nextBoolean()) Assert.assertNull(iter1.next(key));
            else Assert.assertNull(iter2.next(key));
          };
        });
  }
示例#22
0
  @Test
  public void testSpeed() {

    Random rnd = ThreadLocalRandom.current();

    final int IMAGE_SIZE = 28;
    final int BLOCK_COUNT = 10;
    final int FEATURE_SIZE = 9;
    final int FEATURE_COUNT = 10;

    Feature[] features = new Feature[FEATURE_COUNT];
    for (int f = 0; f < features.length; f++) {
      final double mean = f < features.length / 2 ? 0.25 : 0.75;
      features[f] = new Feature(FEATURE_SIZE, mean, 1, Math.pow(0.1, 2), 1);
    }

    byte[][] data = new byte[IMAGE_SIZE][IMAGE_SIZE];
    for (int i = 0; i < data.length; i++) {
      rnd.nextBytes(data[i]);
      if (i < data.length / 2) {
        for (int j = 0; j < data[i].length; j++) {
          data[i][j] = (byte) (+Math.abs(data[i][j]));
        }
      } else {
        for (int j = 0; j < data[i].length; j++) {
          data[i][j] = (byte) (-Math.abs(data[i][j]));
        }
      }
    }

    ByteImage image = new ByteImage(data);
    InferBlocks inferBlocks = new InferBlocks(IMAGE_SIZE, BLOCK_COUNT, features);

    System.out.println("Calculating time...");
    long ms = System.currentTimeMillis();

    for (int s = 1; s <= 10; s++) {

      inferBlocks.infer(image);

      if (s % 10 == 0) {
        System.out.println(
            "Average time (" + s + "): " + (System.currentTimeMillis() - ms) / (double) s);
      }
    }

    System.out.println(
        "Block probs: " + StringUtils.arrayToString(inferBlocks.getBlockProbs(), ", "));
    System.out.println("          X: " + StringUtils.arrayToString(inferBlocks.getBlockX(), ", "));
    System.out.println("          Y: " + StringUtils.arrayToString(inferBlocks.getBlockY(), ", "));

    for (int b = 0; b < BLOCK_COUNT; b++) {
      System.out.println(
          "Block #"
              + (b + 1)
              + " feature probs: "
              + StringUtils.arrayToString(inferBlocks.getBlockFeatureProbs()[b], ", "));
    }
  }
 private static RandomTree randomTree(int minSize, int maxSize) {
   // perform most of our tree constructions via update, as this is more efficient; since every run
   // uses this
   // we test builder disproportionately more often than if it had its own test anyway
   return ThreadLocalRandom.current().nextFloat() < 0.95
       ? randomTreeByUpdate(minSize, maxSize)
       : randomTreeByBuilder(minSize, maxSize);
 }
示例#24
0
 private static IntFunction<Integer> twoDiceThrows() {
   return i -> {
     final ThreadLocalRandom random = ThreadLocalRandom.current();
     final int firstThrow = random.nextInt(1, 7);
     final int secondThrow = random.nextInt(1, 7);
     return firstThrow + secondThrow;
   };
 }
 private static Block createFixWidthValueBlock(int positionCount, int mapSize) {
   BlockBuilder valueBlockBuilder =
       DOUBLE.createBlockBuilder(new BlockBuilderStatus(), positionCount * mapSize);
   for (int i = 0; i < positionCount * mapSize; i++) {
     DOUBLE.writeDouble(valueBlockBuilder, ThreadLocalRandom.current().nextDouble());
   }
   return valueBlockBuilder.build();
 }
 private static String randomString(int length) {
   String symbols = "abcdefghijklmnopqrstuvwxyz";
   char[] chars = new char[length];
   for (int i = 0; i < length; i++) {
     chars[i] = symbols.charAt(ThreadLocalRandom.current().nextInt(symbols.length()));
   }
   return new String(chars);
 }
示例#27
0
 @Override
 public void offerSolution() {
   FitInstance<Instance> solution = task.getFitInstance(stats.getBestInstance());
   System.out.println("Offering solution with f = " + solution.getFitness());
   otherAlgorithms
       .get(ThreadLocalRandom.current().nextInt(otherAlgorithms.size()))
       .acceptSolution(solution);
 }
  @Test
  public void test() throws Exception {
    MmsClient c = createAndConnect();

    new Thread(
            () -> {
              while (received.size() < NUMBER_OF_MESSAGES) {
                rndSleep(300, TimeUnit.MILLISECONDS);
                t.closeIt();
              }
            })
        .start();

    final AtomicInteger ack = new AtomicInteger();

    Runnable server =
        new Runnable() {
          public void run() {
            int latestId = 0;
            Integer ackIt = null;
            while (received.size() < NUMBER_OF_MESSAGES) {
              Message tm = t.take(Message.class);

              if (tm instanceof Broadcast) {
                Broadcast bs = (Broadcast) tm;
                try {
                  BroadcastTestMessage hw = (BroadcastTestMessage) MmsMessage.tryRead(bs);
                  int id = hw.getId();
                  assertEquals(latestId++, id);
                  received.add(id);
                } catch (Exception e) {
                  e.printStackTrace();
                }
                ackIt = null;
              } else {
                if (ackIt == null) {
                  ackIt = ThreadLocalRandom.current().nextInt(ack.get(), latestId + 1);
                }
                ack.set(ackIt);
                latestId = ackIt;
                t.send(new Connected().setSessionId(BIN1).setLastReceivedMessageId((long) ackIt));
              }
            }
          }
        };
    Thread t = new Thread(server);
    t.setUncaughtExceptionHandler((a, b) -> b.printStackTrace());
    t.start();

    for (int i = 0; i < NUMBER_OF_MESSAGES; i++) {
      Thread.sleep(ThreadLocalRandom.current().nextLong(10));
      c.broadcast(new BroadcastTestMessage().setId(i));
    }

    while (received.size() < NUMBER_OF_MESSAGES) {
      Thread.sleep(10);
    }
  }
示例#29
0
  public static void main(String[] args) {
    arrayToSearch = new int[N];

    for (int i = 0; i < N; i++) {
      arrayToSearch[i] = ThreadLocalRandom.current().nextInt(0, 1000);
    }
    ForkJoinPool pool = new ForkJoinPool(NUM_THREADS);
    pool.invoke(new SearchTask(0, N - 1));
  }
示例#30
0
 /**
  * Generates random, smooth and perlin noise images
  *
  * @param args
  * @throws IOException
  */
 public static void main(String[] args) throws IOException {
   float[][] noise =
       PerlinNoiseGenerator.whiteNoise(800, 800, ThreadLocalRandom.current().nextLong());
   ImageIO.write(heightMapToImage(noise), "jpg", new File("noise.jpg"));
   float[][] smooth = PerlinNoiseGenerator.smoothNoise(noise, 0);
   ImageIO.write(heightMapToImage(smooth), "jpg", new File("smooth.jpg"));
   float[][] perlin = PerlinNoiseGenerator.perlinNoise(noise, 15, 0.962F);
   ImageIO.write(heightMapToImage(perlin), "jpg", new File("perlin.jpg"));
 }