1 /*
2 * Licensed to the Apache Software Foundation (ASF) under one
3 * or more contributor license agreements. See the NOTICE file
4 * distributed with this work for additional information
5 * regarding copyright ownership. The ASF licenses this file
6 * to you under the Apache License, Version 2.0 (the
7 * "License"); you may not use this file except in compliance
8 * with the License. You may obtain a copy of the License at
9 *
10 * http://www.apache.org/licenses/LICENSE-2.0
11 *
12 * Unless required by applicable law or agreed to in writing,
13 * software distributed under the License is distributed on an
14 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
15 * KIND, either express or implied. See the License for the
16 * specific language governing permissions and limitations
17 * under the License.
18 */
19 package org.eclipse.aether.internal.impl;
20
21 import java.util.Collection;
22 import java.util.concurrent.atomic.AtomicBoolean;
23
24 import org.eclipse.aether.SyncContext;
25 import org.eclipse.aether.artifact.Artifact;
26 import org.eclipse.aether.metadata.Metadata;
27
28 import static java.util.Objects.requireNonNull;
29
30 /**
31 * A {@link SyncContext} wrapper that delegates {@link #close()} to the underlying context at most once, allowing the
32 * context to be managed with try-with-resources while it is also closed explicitly at an earlier point (e.g. the
33 * shared context must be closed before the resolver switches to the exclusive one). Closing the underlying context
34 * twice is not guaranteed to be harmless by the {@link SyncContext} contract.
35 */
36 final class CloseOnceSyncContext implements SyncContext {
37
38 private final SyncContext delegate;
39 private final AtomicBoolean closed;
40
41 CloseOnceSyncContext(SyncContext delegate) {
42 this.delegate = requireNonNull(delegate);
43 this.closed = new AtomicBoolean(false);
44 }
45
46 @Override
47 public void acquire(Collection<? extends Artifact> artifacts, Collection<? extends Metadata> metadatas) {
48 if (closed.get()) {
49 throw new IllegalStateException("sync context is already closed");
50 }
51 delegate.acquire(artifacts, metadatas);
52 }
53
54 @Override
55 public void close() {
56 if (closed.compareAndSet(false, true)) {
57 delegate.close();
58 }
59 }
60 }