001/** 002 * Java Web Archive Toolkit - Software to read and validate ARC, WARC 003 * and GZip files. (http://jwat.org/) 004 * Copyright 2011-2012 Netarkivet.dk (http://netarkivet.dk/) 005 * 006 * Licensed under the Apache License, Version 2.0 (the "License"); 007 * you may not use this file except in compliance with the License. 008 * You may obtain a copy of the License at 009 * 010 * http://www.apache.org/licenses/LICENSE-2.0 011 * 012 * Unless required by applicable law or agreed to in writing, software 013 * distributed under the License is distributed on an "AS IS" BASIS, 014 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 015 * See the License for the specific language governing permissions and 016 * limitations under the License. 017 */ 018package org.jwat.archive; 019 020import java.util.concurrent.ConcurrentLinkedQueue; 021import java.util.concurrent.Semaphore; 022 023public class ManagedPayloadManager { 024 025 public static final int DEFAULT_COPY_BUFFER_SIZE = 8192; 026 027 public static final int DEFAULT_IN_MEMORY_BUFFER_SIZE = 10*1024*1024; 028 029 public static ManagedPayloadManager getInstance() { 030 return getInstance(DEFAULT_COPY_BUFFER_SIZE, DEFAULT_IN_MEMORY_BUFFER_SIZE); 031 } 032 033 public static ManagedPayloadManager getInstance(int copyBufferSize, int inMemorybufferSize) { 034 ManagedPayloadManager mpm = new ManagedPayloadManager(); 035 mpm.copyBufferSize = copyBufferSize; 036 mpm.inMemorybufferSize = inMemorybufferSize; 037 return mpm; 038 } 039 040 protected Semaphore queueLock = new Semaphore(1); 041 042 protected ConcurrentLinkedQueue<ManagedPayload> managedPayloadQueue = new ConcurrentLinkedQueue<ManagedPayload>(); 043 044 protected int copyBufferSize; 045 046 protected int inMemorybufferSize; 047 048 public ManagedPayload checkout() { 049 ManagedPayload managedPayload = null; 050 queueLock.acquireUninterruptibly(); 051 managedPayload = managedPayloadQueue.poll(); 052 if (managedPayload == null) { 053 managedPayload = new ManagedPayload(copyBufferSize, inMemorybufferSize); 054 } 055 if (!managedPayload.lock.tryAcquire()) { 056 throw new IllegalStateException(); 057 } 058 queueLock.release(); 059 return managedPayload; 060 } 061 062 public void checkin(ManagedPayload managedPayload) { 063 queueLock.acquireUninterruptibly(); 064 managedPayload.lock.release(); 065 managedPayloadQueue.add(managedPayload); 066 queueLock.release(); 067 } 068 069}