SlideShare a Scribd company logo
Java весна 2013 лекция 3
Java весна 2013 лекция 3
Java весна 2013 лекция 3
Java весна 2013 лекция 3
Java весна 2013 лекция 3
Java весна 2013 лекция 3
Java весна 2013 лекция 3
Java весна 2013 лекция 3
Java весна 2013 лекция 3
Java весна 2013 лекция 3
Java весна 2013 лекция 3
Java весна 2013 лекция 3
Java весна 2013 лекция 3
Java весна 2013 лекция 3
Java весна 2013 лекция 3
Java весна 2013 лекция 3
Java весна 2013 лекция 3
public final boolean compareAndSet(int expect, int update) {
return unsafe.compareAndSwapInt(this, valueOffset, expect, update);
}
public final int incrementAndGet() {
while (true) {
int current = get(); //get() возвращает текущее значение (volatile)
int next = current + 1;
if (compareAndSet(current, next))
return next;
}
}
―
―
―
―
―
Java весна 2013 лекция 3
―
―
―
―
―
Java весна 2013 лекция 3
Java весна 2013 лекция 3
Java весна 2013 лекция 3
―
Java весна 2013 лекция 3
public class Address {
static private AtomicInteger abonentIdCreator = new AtomicInteger();
final private int abonentId;
public Address(){
this.abonentId = abonentIdCreator.incrementAndGet();
}
public int hashCode() {
return abonentId;
}
}
public interface Abonent {
Address getAddress();
}
public abstract class Msg {
final private Address from;
final private Address to;
public Msg(Address from, Address to){
this.from = from;
this.to = to;
}
protected Address getFrom(){
return from;
}
protected Address getTo(){
return to;
}
public abstract void exec(Abonent abonent);
}
public abstract class MsgToFrontend extends Msg {
public MsgToFrontend(Address from, Address to) {
super(from, to);
}
public void exec(Abonent abonent) {
if( abonent instanceof Frontend ){
exec((Frontend)abonent);
}
}
public abstract void exec(Frontend frontend);
}
public class MsgUpdateUserId extends MsgToFrontend {
final private int sessionId;
final private int userId;
public GameInfoMsg(Address from, Address to, int sessionId, int userId) {
super(from, to);
this. sessionId = sessionId;
this. userId = userId;
}
public void exec(Frontend frontend) {
frontend.updateUserId(sessionId, userId);
}
}
Msg
MsgToAS MsgToFrontend
MsgUpdateUserIdMsgGetUserId
- Address from
- Address to
- String name
- Integer sessionId
- Integer sessionId
- Integer userId
private Map<Address, ConcurrentLinkedQueue<Msg>> messages
= new HashMap<Address, ConcurrentLinkedQueue<Msg>>();
public void sendMessage(Msg message){
Queue<Msg> messageQueue = messages.get(message.getTo());
messageQueue.add(message);
}
public void execForAbonent(Abonent abonent) {
Queue<Msg> messageQueue = messages.get(abonent.getAddress());
while(!messageQueue.isEmpty()){
Msg message = messageQueue.poll();
message.exec(abonent);
}
}
Java весна 2013 лекция 3
Java весна 2013 лекция 3
public class AddressService {
private Map<Class<?>, Address> addresses = new HashMap<Class<?>, Address>();
public Address getAddress(Class<?> abonentClass) {
return addresses.get(abonentClass);
}
public void setAddress(Abonent abonent) {
addresses.put(abonent.getClass(), abonent.getAddress());
}
}
Java весна 2013 лекция 3
public void run() {
while (true) {
messageSystem.execForAbonent(this);
Thread.sleep(TICK_TIME);
}
}
14. Плюсы и минусы многопоточных приложений
15. Способы взаимодействия потоков
16. java.util.concurrent
17. MessageSystem. Address и Abonent
Java весна 2013 лекция 3
Java весна 2013 лекция 3

More Related Content

DOCX
Implement of c &amp; its coding programming by sarmad baloch
PDF
Base de-datos
PDF
Smart Contract samples
PDF
Async JavaScript in ES7
PDF
Бизнес весна 2014 лекция 6
PPT
Тестирование весна 2014 смешанное занятие 2
PPTX
HighLoad весна 2014 лекция 6
PPTX
Тестирование весна 2014 смешанное занятие 3
Implement of c &amp; its coding programming by sarmad baloch
Base de-datos
Smart Contract samples
Async JavaScript in ES7
Бизнес весна 2014 лекция 6
Тестирование весна 2014 смешанное занятие 2
HighLoad весна 2014 лекция 6
Тестирование весна 2014 смешанное занятие 3

Viewers also liked (15)

PDF
Java осень 2014 занятие 3
PDF
Разработка веб-сервисов осень 2013 лекция 3
PDF
C++ осень 2012 лекция 1
PPTX
АиСД осень 2012 лекция 1
PPTX
C++ осень 2012 лекция 12
PDF
Проектирование графических интерфейсов лекция 6 - часть 1
PDF
Тестирование весна 2013 лекция 5
PDF
Android осень 2013 лекция 1
PPTX
АиСД осень 2012 лекция 11
PPTX
АиСД осень 2012 лекция 12
PDF
Java осень 2013 лекция 1-2
PDF
Java осень 2014 занятие 5
PDF
C++ осень 2012 лекция 7
PPTX
Web осень 2013 лекция 4
PDF
Проектирование графических интерфейсов лекция 1
Java осень 2014 занятие 3
Разработка веб-сервисов осень 2013 лекция 3
C++ осень 2012 лекция 1
АиСД осень 2012 лекция 1
C++ осень 2012 лекция 12
Проектирование графических интерфейсов лекция 6 - часть 1
Тестирование весна 2013 лекция 5
Android осень 2013 лекция 1
АиСД осень 2012 лекция 11
АиСД осень 2012 лекция 12
Java осень 2013 лекция 1-2
Java осень 2014 занятие 5
C++ осень 2012 лекция 7
Web осень 2013 лекция 4
Проектирование графических интерфейсов лекция 1
Ad

Similar to Java весна 2013 лекция 3 (20)

PPTX
Java осень 2012 лекция 3
PPTX
Java весна 2013 лекция 2
PDF
Creating a Facebook Clone - Part XX.pdf
PDF
public class CircularDoublyLinkedList-E- implements List-E- { privat.pdf
PPTX
Laziness, trampolines, monoids and other functional amenities: this is not yo...
PPTX
Code Smells y Refactoring o haciendo que nuestro codigo huela (y se vea) mejo...
PDF
Java: Nie popełniaj tych błędów!
PPTX
Java осень 2012 лекция 2
PPTX
TDC2016POA | Trilha .NET - CQRS e ES na prática com RavenDB
PDF
Here is the editable codeSolutionimport java.util.NoSuchEleme.pdf
PDF
CSC-1106 Homework 09 (Class and static methods) Due Tuesday, Novembe.pdf
PDF
@author public class Person{   String sname, .pdf
PDF
Creating a Facebook Clone - Part XIV.pdf
PPTX
C sharp 8
PDF
How do I fix it in LinkedList.javaLinkedList.java Define.pdf
PDF
How do I fix it in javaLinkedList.java Defines a doubl.pdf
PDF
3. Объекты, классы и пакеты в Java
PDF
import java-util--- public class MyLinkedList{ public static void.pdf
PPTX
Presentation Android Architecture Components
PPTX
TDC2016SP - Trilha .NET
Java осень 2012 лекция 3
Java весна 2013 лекция 2
Creating a Facebook Clone - Part XX.pdf
public class CircularDoublyLinkedList-E- implements List-E- { privat.pdf
Laziness, trampolines, monoids and other functional amenities: this is not yo...
Code Smells y Refactoring o haciendo que nuestro codigo huela (y se vea) mejo...
Java: Nie popełniaj tych błędów!
Java осень 2012 лекция 2
TDC2016POA | Trilha .NET - CQRS e ES na prática com RavenDB
Here is the editable codeSolutionimport java.util.NoSuchEleme.pdf
CSC-1106 Homework 09 (Class and static methods) Due Tuesday, Novembe.pdf
@author public class Person{   String sname, .pdf
Creating a Facebook Clone - Part XIV.pdf
C sharp 8
How do I fix it in LinkedList.javaLinkedList.java Define.pdf
How do I fix it in javaLinkedList.java Defines a doubl.pdf
3. Объекты, классы и пакеты в Java
import java-util--- public class MyLinkedList{ public static void.pdf
Presentation Android Architecture Components
TDC2016SP - Trilha .NET
Ad

More from Technopark (20)

PDF
Лекция 11. Вычислительная модель Pregel
PDF
Лекция 14. Hadoop в Поиске Mail.Ru
PDF
Лекция 13. YARN
PDF
Лекция 12. Spark
PDF
Лекция 10. Apache Mahout
PDF
Лекция 9. ZooKeeper
PDF
Лекция 7. Введение в Pig и Hive
PDF
Лекция 6. MapReduce в Hadoop (графы)
PDF
Лекция 5. MapReduce в Hadoop (алгоритмы)
PDF
Лекция 4. MapReduce в Hadoop (введение)
PDF
Лекция 3. Распределённая файловая система HDFS
PDF
Лекция 2. Основы Hadoop
PDF
Лекция 1. Введение в Big Data и MapReduce
PPTX
СУБД 2013 Лекция №10 "Нереляционное решение в области баз данных — NoSQL"
PPT
СУБД 2013 Лекция №10 "Нереляционное решение в области баз данных — NoSQL" Час...
PPTX
СУБД 2013 Лекция №9 "Безопасность баз данных"
PPTX
СУБД 2013 Лекция №8 "Конфигурирование базы данных"
PPTX
СУБД 2013 Лекция №7 "Оптимизация запросов и индексирование"
PPTX
СУБД 2013 Лекция №5 "Определение узких мест"
PPTX
СУБД 2013 Лекция №6 "Профилирование запросов. Сложноструктурированные SQL-зап...
Лекция 11. Вычислительная модель Pregel
Лекция 14. Hadoop в Поиске Mail.Ru
Лекция 13. YARN
Лекция 12. Spark
Лекция 10. Apache Mahout
Лекция 9. ZooKeeper
Лекция 7. Введение в Pig и Hive
Лекция 6. MapReduce в Hadoop (графы)
Лекция 5. MapReduce в Hadoop (алгоритмы)
Лекция 4. MapReduce в Hadoop (введение)
Лекция 3. Распределённая файловая система HDFS
Лекция 2. Основы Hadoop
Лекция 1. Введение в Big Data и MapReduce
СУБД 2013 Лекция №10 "Нереляционное решение в области баз данных — NoSQL"
СУБД 2013 Лекция №10 "Нереляционное решение в области баз данных — NoSQL" Час...
СУБД 2013 Лекция №9 "Безопасность баз данных"
СУБД 2013 Лекция №8 "Конфигурирование базы данных"
СУБД 2013 Лекция №7 "Оптимизация запросов и индексирование"
СУБД 2013 Лекция №5 "Определение узких мест"
СУБД 2013 Лекция №6 "Профилирование запросов. Сложноструктурированные SQL-зап...

Recently uploaded (20)

PDF
NewMind AI Weekly Chronicles - August'25 Week I
PPTX
sap open course for s4hana steps from ECC to s4
PDF
Review of recent advances in non-invasive hemoglobin estimation
PPT
“AI and Expert System Decision Support & Business Intelligence Systems”
PDF
Blue Purple Modern Animated Computer Science Presentation.pdf.pdf
PPTX
Detection-First SIEM: Rule Types, Dashboards, and Threat-Informed Strategy
PPTX
Digital-Transformation-Roadmap-for-Companies.pptx
PPTX
Spectroscopy.pptx food analysis technology
PDF
KodekX | Application Modernization Development
PDF
Approach and Philosophy of On baking technology
PDF
Encapsulation theory and applications.pdf
PDF
Empathic Computing: Creating Shared Understanding
PDF
Spectral efficient network and resource selection model in 5G networks
PDF
MIND Revenue Release Quarter 2 2025 Press Release
PDF
Building Integrated photovoltaic BIPV_UPV.pdf
DOCX
The AUB Centre for AI in Media Proposal.docx
PPTX
ACSFv1EN-58255 AWS Academy Cloud Security Foundations.pptx
PDF
Reach Out and Touch Someone: Haptics and Empathic Computing
PDF
Unlocking AI with Model Context Protocol (MCP)
PDF
Architecting across the Boundaries of two Complex Domains - Healthcare & Tech...
NewMind AI Weekly Chronicles - August'25 Week I
sap open course for s4hana steps from ECC to s4
Review of recent advances in non-invasive hemoglobin estimation
“AI and Expert System Decision Support & Business Intelligence Systems”
Blue Purple Modern Animated Computer Science Presentation.pdf.pdf
Detection-First SIEM: Rule Types, Dashboards, and Threat-Informed Strategy
Digital-Transformation-Roadmap-for-Companies.pptx
Spectroscopy.pptx food analysis technology
KodekX | Application Modernization Development
Approach and Philosophy of On baking technology
Encapsulation theory and applications.pdf
Empathic Computing: Creating Shared Understanding
Spectral efficient network and resource selection model in 5G networks
MIND Revenue Release Quarter 2 2025 Press Release
Building Integrated photovoltaic BIPV_UPV.pdf
The AUB Centre for AI in Media Proposal.docx
ACSFv1EN-58255 AWS Academy Cloud Security Foundations.pptx
Reach Out and Touch Someone: Haptics and Empathic Computing
Unlocking AI with Model Context Protocol (MCP)
Architecting across the Boundaries of two Complex Domains - Healthcare & Tech...

Java весна 2013 лекция 3

  • 18. public final boolean compareAndSet(int expect, int update) { return unsafe.compareAndSwapInt(this, valueOffset, expect, update); } public final int incrementAndGet() { while (true) { int current = get(); //get() возвращает текущее значение (volatile) int next = current + 1; if (compareAndSet(current, next)) return next; } }
  • 25.
  • 27. public class Address { static private AtomicInteger abonentIdCreator = new AtomicInteger(); final private int abonentId; public Address(){ this.abonentId = abonentIdCreator.incrementAndGet(); } public int hashCode() { return abonentId; } } public interface Abonent { Address getAddress(); }
  • 28. public abstract class Msg { final private Address from; final private Address to; public Msg(Address from, Address to){ this.from = from; this.to = to; } protected Address getFrom(){ return from; } protected Address getTo(){ return to; } public abstract void exec(Abonent abonent); }
  • 29. public abstract class MsgToFrontend extends Msg { public MsgToFrontend(Address from, Address to) { super(from, to); } public void exec(Abonent abonent) { if( abonent instanceof Frontend ){ exec((Frontend)abonent); } } public abstract void exec(Frontend frontend); }
  • 30. public class MsgUpdateUserId extends MsgToFrontend { final private int sessionId; final private int userId; public GameInfoMsg(Address from, Address to, int sessionId, int userId) { super(from, to); this. sessionId = sessionId; this. userId = userId; } public void exec(Frontend frontend) { frontend.updateUserId(sessionId, userId); } }
  • 31. Msg MsgToAS MsgToFrontend MsgUpdateUserIdMsgGetUserId - Address from - Address to - String name - Integer sessionId - Integer sessionId - Integer userId
  • 32. private Map<Address, ConcurrentLinkedQueue<Msg>> messages = new HashMap<Address, ConcurrentLinkedQueue<Msg>>(); public void sendMessage(Msg message){ Queue<Msg> messageQueue = messages.get(message.getTo()); messageQueue.add(message); } public void execForAbonent(Abonent abonent) { Queue<Msg> messageQueue = messages.get(abonent.getAddress()); while(!messageQueue.isEmpty()){ Msg message = messageQueue.poll(); message.exec(abonent); } }
  • 35. public class AddressService { private Map<Class<?>, Address> addresses = new HashMap<Class<?>, Address>(); public Address getAddress(Class<?> abonentClass) { return addresses.get(abonentClass); } public void setAddress(Abonent abonent) { addresses.put(abonent.getClass(), abonent.getAddress()); } }
  • 37. public void run() { while (true) { messageSystem.execForAbonent(this); Thread.sleep(TICK_TIME); } }
  • 38. 14. Плюсы и минусы многопоточных приложений 15. Способы взаимодействия потоков 16. java.util.concurrent 17. MessageSystem. Address и Abonent