001 /*
002 * Copyright 2010 the original author or authors.
003 *
004 * Licensed under the Apache License, Version 2.0 (the "License");
005 * you may not use this file except in compliance with the License.
006 * You may obtain a copy of the License at
007 *
008 * http://www.apache.org/licenses/LICENSE-2.0
009 *
010 * Unless required by applicable law or agreed to in writing, software
011 * distributed under the License is distributed on an "AS IS" BASIS,
012 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
013 * See the License for the specific language governing permissions and
014 * limitations under the License.
015 */
016 package com.hs.mail.util;
017
018 import java.util.NoSuchElementException;
019 import java.util.TreeSet;
020
021 /**
022 *
023 * @author Won Chul Doh
024 * @since Dec 12, 2005
025 *
026 */
027 public class ObjectLocker {
028
029 public static final long DEFAULT_MAX_WAIT = 3L * 1000L;
030 public static final long DEFAULT_MIN_EVICTABLE_TIME_MILLIS = 5L * 60L * 1000L;
031 public static final int DEFAULT_QUEUE_SIZE = 100;
032
033 static TreeSet _locks = new TreeSet();
034
035 public ObjectLocker() {
036 super();
037 }
038
039 protected long _maxWait = DEFAULT_MAX_WAIT;
040 protected long _minEvictableTimeMillis = DEFAULT_MIN_EVICTABLE_TIME_MILLIS;
041 protected int _queueSize = DEFAULT_QUEUE_SIZE;
042
043 public void lock(Object o) throws Exception {
044 long starttime = System.currentTimeMillis();
045 for (;;) {
046 if (_locks.contains(o)) {
047 synchronized (this) {
048 try {
049 wait(_maxWait);
050 } catch (InterruptedException e) {
051 // ignored
052 }
053 }
054 if ((System.currentTimeMillis() - starttime) >= _maxWait) {
055 throw new NoSuchElementException("Timeout waiting for idle object " + o);
056 } else {
057 continue; // keep looping
058 }
059 } else {
060 synchronized (this) {
061 _locks.add(o);
062 }
063 return;
064 }
065 }
066 }
067
068 public void unlock(Object o) {
069 synchronized (this) {
070 _locks.remove(o);
071 if (_locks.size() >= _queueSize) {
072 evict();
073 }
074 notifyAll();
075 }
076 }
077
078 private void evict() {
079 }
080
081 }