- package com.abc.handoff;
- import com.abc.pp.stringhandoff.*;
- import com.programix.thread.*;
- public class StringHandoffImpl implements StringHandoff {
- private boolean isShutdown = false;
- private String message = null;
- private boolean isReceiving = false;
- @Override
- public synchronized void pass(String msg, long msTimeout)
- throws InterruptedException, TimedOutException, ShutdownException, IllegalStateException {
- throwIfShutdownOrPassing();
- passAndNotify(msg);
- long messagesend = System.currentTimeMillis() + msTimeout;
- while ( message != null ) {
- long messagewait = messagesend - System.currentTimeMillis();
- if ( messagewait <= 0 ) {
- throw new TimedOutException();
- }
- wait(messagewait);
- if ( isShutdown ) {
- throw new ShutdownException();
- }
- }
- }
- @Override
- public synchronized void pass(String msg) throws InterruptedException, ShutdownException, IllegalStateException {
- throwIfShutdownOrPassing();
- passAndNotify(msg);
- while ( message != null ) {
- wait();
- if ( isShutdown ) {
- throw new ShutdownException();
- }
- }
- }
- @Override
- public synchronized String receive(long msTimeout)
- throws InterruptedException, TimedOutException, ShutdownException, IllegalStateException {
- throwIfShutdownOrReceiving();
- long messagesend = System.currentTimeMillis() + msTimeout;
- while ( message == null ) {
- long messagewait = messagesend - System.currentTimeMillis();
- if ( messagewait <= 0 ) {
- throw new TimedOutException();
- }
- wait(messagewait);
- if ( isShutdown ) {
- throw new ShutdownException();
- }
- }
- return receiveAndNotify();
- }
- @Override
- public synchronized String receive() throws InterruptedException, ShutdownException, IllegalStateException {
- throwIfShutdownOrReceiving();
- // while there is no message, wait.
- while ( message == null ) {
- wait();
- if ( isShutdown ) {
- throw new ShutdownException();
- }
- }
- return receiveAndNotify();
- }
- @Override
- public synchronized void shutdown() {
- isShutdown = true;
- message = null;
- isReceiving = false;
- notifyAll();
- }
- @Override
- public Object getLockObject() {
- return this;
- }
- private synchronized void passAndNotify(String msg) {
- if (msg == "orange") {
- System.out.println(isReceiving);
- }
- message = msg;
- notifyAll();
- }
- private synchronized String receiveAndNotify() {
- String msg = message;
- message = null;
- isReceiving = false;
- notifyAll();
- return msg;
- }
- private synchronized void throwIfShutdownOrReceiving() throws ShutdownException, IllegalStateException {
- if ( isShutdown ) {
- throw new ShutdownException();
- }
- if ( isReceiving ) {
- throw new IllegalStateException();
- }
- isReceiving = true;
- }
- private synchronized void throwIfShutdownOrPassing() throws ShutdownException, IllegalStateException {
- if ( isShutdown ) {
- throw new ShutdownException();
- }
- if ( message != null ) {
- throw new IllegalStateException();
- }
- }
- }