public void givenStatesAndMsg_whenCheckStateEvalsFalse_throwsException() {
    int[] validStates = { -1, 0, 1 };
    int givenState = 10;
    String message = "You have entered an invalid state";
  
    assertThatThrownBy(
      () -> Preconditions.checkState(
        Arrays.binarySearch(validStates, givenState) > 0, message))
      .isInstanceOf(IllegalStateException.class)
      .hasMessageStartingWith(message).hasNoCause();
}

        

public static void main(String[] args) {

	//Throws IllegalStateException - if expression is false
	//Preconditions.checkState(expression, errorMessage)

	Student student = new Student("Sriram", 2, "Chess");
	Student student2 = new Student("Charan", 8, "Cricket");

	/**
	 * Negative case
	 */
	try {
		Preconditions.checkState(student2.isKid(), 
				"This program requires Students below 5 years, but found %s", student2.getAge());
	} catch (IllegalStateException e) {
		System.out.println(e);
	}

	/**
	 * Positive case
	 */
	Preconditions.checkState(student.isKid(), 
			"This program requires Students below 5 years, but found %s", student.getAge());

	System.out.println("Thanks for providing valid input");
}

        

public void overloadSelection() {
	Boolean boxedBoolean = null;
	boolean aBoolean = true;
	Long boxedLong = null;
	int anInt = 1;
	// With a boxed predicate, no overloads can be selected in phase 1
	// ambiguous without the call to .booleanValue to unbox the Boolean
	checkState(boxedBoolean.booleanValue(), "",  1);
	// ambiguous without the cast to Object because the boxed predicate prevents any overload from
	// being selected in phase 1
	checkState(boxedBoolean, "", (Object) boxedLong);

	// ternaries introduce their own problems. because of the ternary (which requires a boxing
	// operation) no overload can be selected in phase 1.  and in phase 2 it is ambiguous since it
	// matches with the second parameter being boxed and without it being boxed.  The cast to Object
	// avoids this.
	checkState(aBoolean, "", aBoolean ? "" : anInt, (Object) anInt);

	// ambiguous without the .booleanValue() call since the boxing forces us into phase 2 resolution
	short s = 2;
	checkState(boxedBoolean.booleanValue(), "", s);
}

        

public void testState() {
	checkState(this.initialized, "Cannot perform action because not initialized.");
}

        

public void testCheckState_complexMessage_failure() {
	try {
		Preconditions.checkState(false, FORMAT, 5);
		fail("no exception thrown");
	} catch (IllegalStateException expected) {
		verifyComplexMessage(expected);
	}
}

        

protected BasicTransactionSemantics createTransaction() {
  if (!open) {
    String msg = "Channel closed " + channelNameDescriptor;
    if (startupError != null) {
      msg += ". Due to " + startupError.getClass().getName() + ": " +
          startupError.getMessage();
      throw new IllegalStateException(msg, startupError);
    }
    throw new IllegalStateException(msg);
  }

  FileBackedTransaction trans = transactions.get();
  if (trans != null && !trans.isClosed()) {
    Preconditions.checkState(false,
        "Thread has transaction which is still open: " +
            trans.getStateAsString() + channelNameDescriptor);
  }
  trans = new FileBackedTransaction(log, TransactionIDOracle.next(),
      transactionCapacity, keepAlive, queueRemaining, getName(),
      fsyncPerTransaction, channelCounter);
  transactions.set(trans);
  return trans;
}

        

private GrpcEngine getGrpcEngine(String registryAddress, int registryPort) {
    String key = registryAddress + ":" + registryPort;
    LOCK.lock();
    try {
        GrpcEngine engine = ENGINES.get(key);
        if (engine != null) {
            return engine;
        }
        Preconditions.checkNotNull(registryAddress, "registryAddress  is not Null", registryAddress);
        Preconditions.checkState(registryPort != 0, "RegistryPort can not be zero", registryPort);
        GrpcURL registryUrl = new GrpcURL(Constants.REGISTRY_PROTOCOL, registryAddress, registryPort);
        engine = new GrpcEngine(registryUrl);
        ENGINES.put(key, engine);
        return engine;
    } finally {
        LOCK.unlock();
    }
}

        

void close() {
  String suffix = "";
  
  Preconditions.checkState(refCount == 0,
      "tried to close replica with refCount %d: %s", refCount, this);
  refCount = -1;
  Preconditions.checkState(purged,
      "tried to close unpurged replica %s", this);
  if (hasMmap()) {
    munmap();
    if (LOG.isTraceEnabled()) {
      suffix += "  munmapped.";
    }
  }
  IOUtils.cleanup(LOG, dataStream, metaStream);
  if (slot != null) {
    cache.scheduleSlotReleaser(slot);
    if (LOG.isTraceEnabled()) {
      suffix += "  scheduling " + slot + " for later release.";
    }
  }
  if (LOG.isTraceEnabled()) {
    LOG.trace("closed " + this + suffix);
  }
}

        

void readyTransaction(@Nonnull final PingPongTransaction tx) {
    // First mark the transaction as not locked.
    final boolean lockedMatch = LOCKED_UPDATER.compareAndSet(this, tx, null);
    Preconditions.checkState(lockedMatch, "Attempted to submit transaction %s while we have %s", tx, lockedTx);
    LOG.debug("Transaction {} unlocked", tx);

    /*
     * The transaction is ready. It will then be picked up by either next allocation,
     * or a background transaction completion callback.
     */
    final boolean success = READY_UPDATER.compareAndSet(this, null, tx);
    Preconditions.checkState(success, "Transaction %s collided on ready state", tx, readyTx);
    LOG.debug("Transaction {} readied", tx);

    /*
     * We do not see a transaction being in-flight, so we need to take care of dispatching
     * the transaction to the backend. We are in the ready case, we cannot short-cut
     * the checking of readyTx, as an in-flight transaction may have completed between us
     * setting the field above and us checking.
     */
    if (inflightTx == null) {
        synchronized (this) {
            processIfReady();
        }
    }
}

        

public Collection<EditLogInputStream> selectInputStreams(
    long fromTxId, long toAtLeastTxId, MetaRecoveryContext recovery,
    boolean inProgressOk) throws IOException {

  List<EditLogInputStream> streams = new ArrayList<EditLogInputStream>();
  synchronized(journalSetLock) {
    Preconditions.checkState(journalSet.isOpen(), "Cannot call " +
        "selectInputStreams() on closed FSEditLog");
    selectInputStreams(streams, fromTxId, inProgressOk);
  }

  try {
    checkForGaps(streams, fromTxId, toAtLeastTxId, inProgressOk);
  } catch (IOException e) {
    if (recovery != null) {
      // If recovery mode is enabled, continue loading even if we know we
      // can't load up to toAtLeastTxId.
      LOG.error(e);
    } else {
      closeAllStreams(streams);
      throw e;
    }
  }
  return streams;
}        
main