2014-05-10 22:30

题目链接

原题:

Design database locks to allow r/w concurrency and data consistency.

题目:设计一个支持并行读写并保证数据一致性的数据库锁。

解法:这是什么范畴的面试题?对于我这种完全没有相关项目经验的人,还真是无从下手。翻了书之后顺便重新复习了一下共享锁、互斥锁的概念。说白了,这些都是课本上的基础知识,可是毕业没多久就忘光了。看来知识不用,保质期比水果还短。然后我琢磨着锁的模型,写了个模拟的代码。这个代码和SQL毫无关系,可能也和正确答案相去甚远。姑妄言之,姑妄听之吧。

代码:

 1 // http://www.careercup.com/question?id=6366101810184192
 2 import java.util.concurrent.Semaphore;
 3 
 4 public class FooBar {
 5     public static final int MAX_CONCURRENT_READ = 100;
 6     private Semaphore sharedSemaphore;
 7     private Semaphore exclusiveSemaphore;
 8 
 9     public FooBar() {
10         // TODO Auto-generated constructor stub
11         this.sharedSemaphore = new Semaphore(MAX_CONCURRENT_READ);
12         this.exclusiveSemaphore = new Semaphore(1);
13     }
14 
15     public void reader() {
16         // The reader here is not to return a value, but to perform read()
17         // action. Thus it is 'void reader()'.
18         while (exclusiveSemaphore.availablePermits() < 1) {
19             try {
20                 Thread.sleep(50);
21             } catch (InterruptedException e) {
22                 // TODO Auto-generated catch block
23                 e.printStackTrace();
24             }
25         }
26 
27         try {
28             sharedSemaphore.acquire();
29             System.out.println("Performing read() operation.");
30             sharedSemaphore.release();
31         } catch (InterruptedException e) {
32             // TODO Auto-generated catch block
33             e.printStackTrace();
34         }
35     }
36 
37     public void writer() {
38         while (exclusiveSemaphore.availablePermits() < 1
39                 && sharedSemaphore.availablePermits() < MAX_CONCURRENT_READ) {
40             try {
41                 Thread.sleep(50);
42             } catch (InterruptedException e) {
43                 // TODO Auto-generated catch block
44                 e.printStackTrace();
45             }
46         }
47 
48         try {
49             exclusiveSemaphore.acquire();
50             System.out.println("Performing write() operation.");
51             exclusiveSemaphore.release();
52         } catch (InterruptedException e) {
53             // TODO Auto-generated catch block
54             e.printStackTrace();
55         }
56     }
57 
58     public static void main(String[] args) {
59         FooBar fooBar = new FooBar();
60 
61         fooBar.reader();
62         fooBar.writer();
63     }
64 }

 

 posted on 2014-05-10 22:49  zhuli19901106  阅读(169)  评论(0编辑  收藏  举报