AsyncContextSynchronizer.java 1.9 KB
Newer Older
A
Arjen Poutsma 已提交
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69
/*
 * Copyright 2002-2015 the original author or authors.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package org.springframework.rx.web.servlet;

import java.io.IOException;
import java.util.concurrent.atomic.AtomicInteger;
import javax.servlet.AsyncContext;
import javax.servlet.ServletInputStream;
import javax.servlet.ServletOutputStream;

/**
 * @author Arjen Poutsma
 */
class AsyncContextSynchronizer {

	private static final int READ_COMPLETE = 1;

	private static final int WRITE_COMPLETE = 1 << 1;

	private static final int COMPLETE = READ_COMPLETE | WRITE_COMPLETE;

	private final AsyncContext asyncContext;

	private final AtomicInteger complete = new AtomicInteger(0);

	public AsyncContextSynchronizer(AsyncContext asyncContext) {
		this.asyncContext = asyncContext;
	}

	public ServletInputStream getInputStream() throws IOException {
		return this.asyncContext.getRequest().getInputStream();
	}

	public ServletOutputStream getOutputStream() throws IOException {
		return this.asyncContext.getResponse().getOutputStream();
	}

	public void readComplete() {
		if (complete.compareAndSet(WRITE_COMPLETE, COMPLETE)) {
			this.asyncContext.complete();
		}
		else {
			this.complete.compareAndSet(0, READ_COMPLETE);
		}
	}

	public void writeComplete() {
		if (complete.compareAndSet(READ_COMPLETE, COMPLETE)) {
			this.asyncContext.complete();
		}
		else {
			this.complete.compareAndSet(0, WRITE_COMPLETE);
		}
	}
}