blob: 32885d03b18fcf0de47ce43a39a5cae613a257a2 (
plain) (
blame)
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
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
|
/*****************************************************************************
* Copyright (c) 2015 CEA LIST.
*
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* Camille Letavernier (CEA LIST) camille.letavernier@cea.fr - Initial API and implementation
*****************************************************************************/
package org.eclipse.papyrus.migration.rsa.concurrent;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReadWriteLock;
import java.util.concurrent.locks.ReentrantReadWriteLock;
import org.eclipse.emf.common.util.URI;
import org.eclipse.emf.ecore.resource.Resource;
/**
* This class is used to synchronize access to physical EMF Resources (Load/Save)
*
* @author Camille Letavernier
*
*/
public class ResourceAccessHelper {
public static ResourceAccessHelper INSTANCE = new ResourceAccessHelper();
private final Map<URI, ReadWriteLock> locks = new HashMap<URI, ReadWriteLock>();
private ResourceAccessHelper() {
// Singleton
}
private Lock getSaveLock(Resource resource) {
ReadWriteLock lock = getLock(resource);
return lock.writeLock();
}
private Lock getLoadLoack(Resource resource) {
ReadWriteLock lock = getLock(resource);
return lock.readLock();
}
/**
* Saves a resource in a thread-safe way. Ensures that the underlying physical
* resource is not being read during the save action
*
* @param resource
* @param options
* @throws IOException
*/
public void saveResource(Resource resource, Map<?, ?> options) throws IOException {
Lock lock = getSaveLock(resource);
lock.lock();
try {
resource.save(options);
} finally {
lock.unlock();
}
}
/**
* Loads a resource in a thread-safe way. Ensures that the underlying physical
* resource is not being saved during the load action. Concurrent read operations
* may still happen
*
* @param resource
* @param options
* @throws IOException
*/
public void loadResource(Resource resource, Map<?, ?> options) throws IOException {
Lock lock = getLoadLoack(resource);
lock.lock();
try {
resource.load(options);
} finally {
lock.unlock();
}
}
private ReadWriteLock getLock(Resource resource) {
URI uri = resource.getURI();
if (uri == null) {
return null;
}
synchronized (this) {
if (!locks.containsKey(uri)) {
locks.put(uri, new ReentrantReadWriteLock());
}
return locks.get(uri);
}
}
}
|