# Channel with sliding window buffer?

**URL:** <https://discourse.julialang.org/t/channel-with-sliding-window-buffer/68647>\
**Category:** General Usage\
**Tags:** channel, concurrency\
**Created:** [September 23, 2021, 8:16pm UTC](https://discourse.julialang.org/t/channel-with-sliding-window-buffer/68647 "2021-09-23T20:16:42Z")\
**Posts on this page:** 1\
**Page:** 1

<div class="post-metadata">

**Author:** ![vshesh](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/vshesh/32/20362_2.png) [@vshesh](https://discourse.julialang.org/u/vshesh)\
**Post date:** [September 23, 2021, 8:16pm UTC](https://discourse.julialang.org/t/channel-with-sliding-window-buffer/68647/1 "2021-09-23T20:16:42Z")

</div>

Are there any versions of julia channels that do not block when they are full?  
I’m looking for a channel that will do a sliding window (so drop the front of the queue when adding something to the back if it’s full). Does that exist? (I tried looking at juliapackages and here on discord and didn’t find anything)

This is a basic idea of how i could imagine using it:

```julia
> c = SlidingWindowChannel(1) # 1 = size of buffer
> put!(c, 1)
> put!(c, 2) # doesn't block
> take!(c)
2
> take!(c) # blocks because buffer has length 1 and it was emptied earlier

```

If it doesn’t exist, how would I implement it?

```julia
import Base.take!, Base.put!

struct SlidingWindowChannel
  c::Channel
end

function SlidingWindowChannel(size::Int=1)
  if size < 1 
    error("SlidingWindowChannel needs to have a buffer of at least 1, got $size.")
  end
  SlidingWindowChannel(Channel(size))
end

Base.take!(swc::SlidingWindowChannel) = Base.take!(swc.c)

function Base.put!(swc::SlidingWindowChannel, v::Any) 
  # from: https://discourse.julialang.org/t/function-to-check-if-channel-is-full/44795
  if length(swc.c.data) >= swc.c.sz_max
    Base.take!(swc)
  end
  Base.put!(swc.c, v)
end

```

Is that it? I don’t think the `put!` function is thread safe.
